int get_addr_from_device(const char *device_name, in_addr_t *addrp){ int _sock_fd; struct ifconf conf; struct ifreq *ifr; char buff[1024]; int num; int i; if (!addrp) { return -1; } _sock_fd = socket(PF_INET, SOCK_DGRAM, 0); if ( _sock_fd < 0 ) return -1; conf.ifc_len = sizeof(buff); conf.ifc_buf = buff; if (ioctl(_sock_fd, SIOCGIFCONF, &conf) < 0) { close(_sock_fd); return -1; } num = conf.ifc_len / sizeof(struct ifreq); ifr = conf.ifc_req; for (i = 0; i < num; i++) { struct sockaddr_in *sin = (struct sockaddr_in *)(&ifr->ifr_addr); if (ioctl(_sock_fd, SIOCGIFFLAGS, ifr) < 0) { close(_sock_fd); return -1; } if ((ifr->ifr_flags & IFF_UP) && strcmp(device_name, ifr->ifr_name) == 0) { memcpy(addrp, &(sin->sin_addr.s_addr), sizeof(in_addr_t)); close(_sock_fd); return 0; } ifr++; } close(_sock_fd); return -1;}