根据网卡名称编号获取指定网卡的IP地址

getIPByIfName(const char *ifNmae)

{

int s;

struct ifreq ifr;

static char *none_ip="0.0.0.0";

if(NULL==ifName)

return none_ip;

s=::socket(AF_INET, SOCK_DGRAM, 0);

if(-1==s)

return none_ip;

bzero(ifr.ifr_name, sizeof(ifr.ifr_name));

strncpy(ifr.ifr_name, ifName, sizeof(ifr.ifr_name)-1);

if(-1==ioctl(s, SIOCGIFADDR, &ifr))

{

TEMP_FAILURE_ERTRY(::close(s));

return none_ip;

}

TEMP_FAILURE_ENTRY(::close(s));

return inet_ntoa(((struct sockaddr_in *) &ifr.ifr_addr)->sin_addr);

}

 

你可能感兴趣的:(socket,struct,null)