在很多时候需要得到本地的Ip地址,又没有配置文件可以读取,可以用下面了这个函数来获得:
string getLocalIp()
{
char ip[128] = {0};
char buff[BUFSIZ];
struct ifconf conf;
conf.ifc_len = BUFSIZ;
conf.ifc_buf = buff;
const int s = socket(PF_INET, SOCK_DGRAM, 0);
ioctl(s, SIOCGIFCONF, &conf);
const int num = conf.ifc_len / sizeof(struct ifreq);
const struct ifreq *ifr = conf.ifc_req;
for(int cnt = 0 ; cnt < num; ++cnt)
{
const struct sockaddr_in *sin = (struct sockaddr_in *) (&ifr->ifr_addr);
ioctl(s, SIOCGIFFLAGS, ifr);
if(((ifr->ifr_flags & IFF_LOOPBACK) == 0) && (ifr->ifr_flags & IFF_UP))
{
inet_ntop(PF_INET, &sin->sin_addr, ip, 128);
printf("%s (%s)\n", ifr->ifr_name, inet_ntop(PF_INET, &sin->sin_addr, ip, 128));
cout <<"ip = "<< ip << endl;
break;
}
ifr++;
}
::close(s);
return string(ip);
}
在网上很多获取本地Ip的方法会造成fd的泄露,原因是它没有关闭fd,即:::close(s)。