//传入的参数是接口名,如eth0,eth1等,返回值是ip地址
char * get_iface_ip(const char *ifname)
{
#if defined(__linux__)
struct ifreq if_data;
struct in_addr in;
char *ip_str;
int sockd;
u_int32_t ip;
/* Create a socket */
if ((sockd = socket (AF_INET, SOCK_PACKET, htons(0x8086))) < 0) {
debug(LOG_ERR, "socket(): %s", strerror(errno));
return NULL;
}
/* Get IP of internal interface */
strcpy (if_data.ifr_name, ifname);
/* Get the IP address */
if (ioctl (sockd, SIOCGIFADDR, &if_data) < 0) {
debug(LOG_ERR, "ioctl(): SIOCGIFADDR %s", strerror(errno));
return NULL;
}
memcpy ((void *) &ip, (void *) &if_data.ifr_addr.sa_data + 2, 4);
in.s_addr = ip;
ip_str = inet_ntoa(in);
close(sockd);
return safe_strdup(ip_str);
#elif defined(__NetBSD__)
struct ifaddrs *ifa, *ifap;
char *str = NULL;
if (getifaddrs(&ifap) == -1) {
debug(LOG_ERR, "getifaddrs(): %s", strerror(errno));
return NULL;
}
/* XXX arbitrarily pick the first IPv4 address */
for (ifa = ifap; ifa != NULL; ifa = ifa->ifa_next) {
if (strcmp(ifa->ifa_name, ifname) == 0 &&
ifa->ifa_addr->sa_family == AF_INET)
break;
}
if (ifa == NULL) {
debug(LOG_ERR, "%s: no IPv4 address assigned");
goto out;
}
str = safe_strdup(inet_ntoa(
((struct sockaddr_in *)ifa->ifa_addr)->sin_addr));
out:
freeifaddrs(ifap);
return str;
#else
return safe_strdup("0.0.0.0");
#endif
}