- int fd, nipaddr;
-#ifdef HAVE_SOCKADDR_SA_LEN
- int n;
-#endif
- struct ifreq *ifrp, *ifend, *ifnext;
- struct sockaddr_in *addr_sin;
- struct IFADDRLIST *al;
- struct ifconf ifc;
- struct ifreq ifr;
- /* Was on stack, but 32k is a bit too much: */
- struct ifreq *ibuf = xmalloc(IFREQ_BUFSIZE * sizeof(ibuf[0]));
- struct IFADDRLIST *st_ifaddrlist;
-
- fd = xsocket(AF_INET, SOCK_DGRAM, 0);
-
- ifc.ifc_len = IFREQ_BUFSIZE * sizeof(ibuf[0]);
- ifc.ifc_buf = (caddr_t)ibuf;
-
- if (ioctl(fd, SIOCGIFCONF, (char *)&ifc) < 0
- || ifc.ifc_len < (int)sizeof(struct ifreq)
- ) {
- if (errno == EINVAL)
- bb_error_msg_and_die(
- "SIOCGIFCONF: ifreq struct too small (%u bytes)",
- (unsigned)(IFREQ_BUFSIZE * sizeof(ibuf[0])));
- bb_perror_msg_and_die("SIOCGIFCONF");
- }
- ifrp = ibuf;
- ifend = (struct ifreq *)((char *)ibuf + ifc.ifc_len);
-
- nipaddr = 1 + (ifc.ifc_len / sizeof(struct ifreq));
- st_ifaddrlist = xzalloc(nipaddr * sizeof(struct IFADDRLIST));
- al = st_ifaddrlist;
- nipaddr = 0;
-
- for (; ifrp < ifend; ifrp = ifnext) {
-#ifdef HAVE_SOCKADDR_SA_LEN
- n = ifrp->ifr_addr.sa_len + sizeof(ifrp->ifr_name);
- if (n < sizeof(*ifrp))
- ifnext = ifrp + 1;
- else
- ifnext = (struct ifreq *)((char *)ifrp + n);
- if (ifrp->ifr_addr.sa_family != AF_INET)
- continue;
-#else
- ifnext = ifrp + 1;
-#endif
- /*
- * Need a template to preserve address info that is
- * used below to locate the next entry. (Otherwise,
- * SIOCGIFFLAGS stomps over it because the requests
- * are returned in a union.)
- */
- strncpy(ifr.ifr_name, ifrp->ifr_name, sizeof(ifr.ifr_name));
- if (ioctl(fd, SIOCGIFFLAGS, (char *)&ifr) < 0) {
- if (errno == ENXIO)
- continue;
- bb_perror_msg_and_die("SIOCGIFFLAGS: %.*s",
- (int)sizeof(ifr.ifr_name), ifr.ifr_name);
- }
-
- /* Must be up */
- if ((ifr.ifr_flags & IFF_UP) == 0)
- continue;
-
- safe_strncpy(al->device, ifr.ifr_name, sizeof(ifr.ifr_name) + 1);
-#ifdef sun
- /* Ignore sun virtual interfaces */
- if (strchr(al->device, ':') != NULL)
- continue;
-#endif
- ioctl_or_perror_and_die(fd, SIOCGIFADDR, (char *)&ifr,
- "SIOCGIFADDR: %s", al->device);
-
- addr_sin = (struct sockaddr_in *)&ifr.ifr_addr;
- al->addr = addr_sin->sin_addr.s_addr;
- ++al;
- ++nipaddr;
- }
- if (nipaddr == 0)
- bb_error_msg_and_die("can't find any network interfaces");
-
- free(ibuf);
- close(fd);
- *ipaddrp = st_ifaddrlist;
- return nipaddr;
-}
-
-
-static void
-setsin(struct sockaddr_in *addr_sin, uint32_t addr)