获取网卡对应IP地址(其中eth是网卡名字 如“eth0” “eth1” “en0” "en1"等, ipstr是输出参数)
static int get_local_ip(const char *eth_inf, char *ipstr)
{
int sd;
struct sockaddr_in sin;
struct ifreq ifr;
sd = socket(AF_INET, SOCK_DGRAM, 0);
if (-1 == sd) {
printf("socket error: %s\n", strerror(errno));
return -1;
}
strncpy(ifr.ifr_name, eth_inf, IFNAMSIZ);
ifr.ifr_name[IFNAMSIZ - 1] = 0;
if (ioctl(sd, SIOCGIFADDR, &ifr) < 0) {
printf("ioctl error: %s\n", strerror(errno));
close(sd);
return -2;
}
memcpy(&sin, &ifr.ifr_addr, sizeof(sin));
snprintf(ipstr, IP_SIZE, "%s", inet_ntoa(sin.sin_addr));
close(sd);
return 0;
}