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>
40 * Return a random link local IP (in host byte order)
42 uint32_t ipv4ll_random_ip(void)
48 dhcp_get_random(&rand);
50 tmp = tmp & IN_CLASSB_HOST;
51 } while (tmp > (IN_CLASSB_HOST - 0x0200));
52 return ((LINKLOCAL_ADDR + 0x0100) + tmp);
56 * Return a random delay in range of zero to secs*1000
58 guint ipv4ll_random_delay_ms(guint secs)
62 dhcp_get_random(&rand);
63 return rand % (secs * 1000);
66 int ipv4ll_send_arp_packet(uint8_t* source_eth, uint32_t source_ip,
67 uint32_t target_ip, int ifindex)
69 struct sockaddr_ll dest;
75 fd = socket(PF_PACKET, SOCK_DGRAM | SOCK_CLOEXEC, htons(ETH_P_ARP));
79 memset(&dest, 0, sizeof(dest));
80 memset(&p, 0, sizeof(p));
82 dest.sll_family = AF_PACKET;
83 dest.sll_protocol = htons(ETH_P_ARP);
84 dest.sll_ifindex = ifindex;
85 dest.sll_halen = ETH_ALEN;
86 memset(dest.sll_addr, 0xFF, ETH_ALEN);
87 if (bind(fd, (struct sockaddr *)&dest, sizeof(dest)) < 0) {
92 ip_source = htonl(source_ip);
93 ip_target = htonl(target_ip);
94 p.arp_hrd = htons(ARPHRD_ETHER);
95 p.arp_pro = htons(ETHERTYPE_IP);
98 p.arp_op = htons(ARPOP_REQUEST);
100 memcpy(&p.arp_sha, source_eth, ETH_ALEN);
101 memcpy(&p.arp_spa, &ip_source, sizeof(p.arp_spa));
102 memcpy(&p.arp_tpa, &ip_target, sizeof(p.arp_tpa));
104 n = sendto(fd, &p, sizeof(p), 0,
105 (struct sockaddr*) &dest, sizeof(dest));
114 int ipv4ll_arp_socket(int ifindex)
117 struct sockaddr_ll sock;
119 fd = socket(PF_PACKET, SOCK_DGRAM | SOCK_CLOEXEC, htons(ETH_P_ARP));
123 memset(&sock, 0, sizeof(sock));
125 sock.sll_family = AF_PACKET;
126 sock.sll_protocol = htons(ETH_P_ARP);
127 sock.sll_ifindex = ifindex;
129 if (bind(fd, (struct sockaddr *) &sock, sizeof(sock)) != 0) {