3 * IPV4 Local Link library with GLib integration
5 * Copyright (C) 2009-2010 Aldebaran Robotics. All rights reserved.
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License version 2 as
9 * published by the Free Software Foundation.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
27 #include <sys/socket.h>
28 #include <sys/types.h>
29 #include <netpacket/packet.h>
30 #include <net/ethernet.h>
31 #include <netinet/if_ether.h>
33 #include <arpa/inet.h>
39 * Return a random link local IP
41 uint32_t ipv4ll_random_ip(int seed)
49 gettimeofday(&tv, NULL);
54 tmp = tmp & IN_CLASSB_HOST;
55 } while (tmp > (IN_CLASSB_HOST - 0x0200));
56 return ((LINKLOCAL_ADDR + 0x0100) + tmp);
60 * Return a random delay in range of zero to secs*1000
62 guint ipv4ll_random_delay_ms(guint secs)
67 gettimeofday(&tv, NULL);
70 return tmp % (secs * 1000);
73 int ipv4ll_send_arp_packet(uint8_t* source_eth, uint32_t source_ip,
74 uint32_t target_ip, int ifindex)
76 struct sockaddr_ll dest;
82 fd = socket(PF_PACKET, SOCK_DGRAM | SOCK_CLOEXEC, htons(ETH_P_ARP));
86 memset(&dest, 0, sizeof(dest));
87 memset(&p, 0, sizeof(p));
89 dest.sll_family = AF_PACKET;
90 dest.sll_protocol = htons(ETH_P_ARP);
91 dest.sll_ifindex = ifindex;
92 dest.sll_halen = ETH_ALEN;
93 memset(dest.sll_addr, 0xFF, ETH_ALEN);
94 if (bind(fd, (struct sockaddr *)&dest, sizeof(dest)) < 0) {
99 ip_source = htonl(source_ip);
100 ip_target = htonl(target_ip);
101 p.arp_hrd = htons(ARPHRD_ETHER);
102 p.arp_pro = htons(ETHERTYPE_IP);
103 p.arp_hln = ETH_ALEN;
105 p.arp_op = htons(ARPOP_REQUEST);
107 memcpy(&p.arp_sha, source_eth, ETH_ALEN);
108 memcpy(&p.arp_spa, &ip_source, sizeof(p.arp_spa));
109 memcpy(&p.arp_tpa, &ip_target, sizeof(p.arp_tpa));
111 n = sendto(fd, &p, sizeof(p), 0,
112 (struct sockaddr*) &dest, sizeof(dest));
121 int ipv4ll_arp_socket(int ifindex)
124 struct sockaddr_ll sock;
125 fd = socket(PF_PACKET, SOCK_DGRAM | SOCK_CLOEXEC, htons(ETH_P_ARP));
129 sock.sll_family = AF_PACKET;
130 sock.sll_protocol = htons(ETH_P_ARP);
131 sock.sll_ifindex = ifindex;
133 if (bind(fd, (struct sockaddr *) &sock, sizeof(sock)) != 0) {