1 /* vi: set sw=4 ts=4: */
3 * socket.c -- DHCP server client/server socket creation
6 * Copyright (C) 1999 Matthew Ramsay <matthewr@moreton.com.au>
7 * Chris Trew <ctrew@moreton.com.au>
9 * Rewrite by Russ Dill <Russ.Dill@asu.edu> July 2001
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program; if not, write to the Free Software
23 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
28 #if (defined(__GLIBC__) && __GLIBC__ >= 2 && __GLIBC_MINOR__ >= 1) || defined _NEWLIB_VERSION
29 #include <netpacket/packet.h>
30 #include <net/ethernet.h>
32 #include <asm/types.h>
33 #include <linux/if_packet.h>
34 #include <linux/if_ether.h>
40 int read_interface(const char *interface, int *ifindex, uint32_t *addr, uint8_t *arp)
44 struct sockaddr_in *our_ip;
46 memset(&ifr, 0, sizeof(ifr));
47 fd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
49 bb_perror_msg("socket failed");
53 ifr.ifr_addr.sa_family = AF_INET;
54 strncpy(ifr.ifr_name, interface, sizeof(ifr.ifr_name));
56 if (ioctl(fd, SIOCGIFADDR, &ifr) != 0) {
57 bb_perror_msg("SIOCGIFADDR failed (is interface %s "
58 "up and configured?)", interface);
62 our_ip = (struct sockaddr_in *) &ifr.ifr_addr;
63 *addr = our_ip->sin_addr.s_addr;
64 DEBUG("%s (our ip) = %s", ifr.ifr_name, inet_ntoa(our_ip->sin_addr));
68 if (ioctl(fd, SIOCGIFINDEX, &ifr) != 0) {
69 bb_perror_msg("SIOCGIFINDEX failed");
73 DEBUG("adapter index %d", ifr.ifr_ifindex);
74 *ifindex = ifr.ifr_ifindex;
78 if (ioctl(fd, SIOCGIFHWADDR, &ifr) != 0) {
79 bb_perror_msg("SIOCGIFHWADDR failed");
83 memcpy(arp, ifr.ifr_hwaddr.sa_data, 6);
84 DEBUG("adapter hardware address %02x:%02x:%02x:%02x:%02x:%02x",
85 arp[0], arp[1], arp[2], arp[3], arp[4], arp[5]);
92 int listen_socket(uint32_t ip, int port, const char *inf)
94 struct ifreq interface;
96 struct sockaddr_in addr;
98 DEBUG("Opening listen socket on 0x%08x:%d %s", ip, port, inf);
99 fd = xsocket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
101 memset(&addr, 0, sizeof(addr));
102 addr.sin_family = AF_INET;
103 addr.sin_port = htons(port);
104 addr.sin_addr.s_addr = ip;
106 if (setsockopt_reuseaddr(fd) == -1) {
110 if (setsockopt_broadcast(fd) == -1) {
115 strncpy(interface.ifr_name, inf, IFNAMSIZ);
116 if (setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, &interface, sizeof(interface)) < 0) {
121 if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {