码迷,mamicode.com
首页 > 其他好文 > 详细

获取本地主机ip

时间:2015-05-28 19:54:25      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:

Windows平台:

char* getlocalhostip ()

{

char *ip=NULL;

WORD wVersionRequested;

WSADATA wsaData;

char name[255];

PHOSTENT hostinfo;

wVersionRequested = MAKEWORD(2,0);

if(WSAStartup(wVersionRequested, &wsaData) == 0)

{

if(gethostname(name, sizeof(name)) == 0)

{

if((hostinfo = gethostbyname(name)) != NULL)

{

ip = inet_ntoa(*(struct in_addr *)*hostinfo->h_addr_list);

}

}

WSACleanup();

}

return ip;

}

Linux平台:

char* getlocalhostip ()

int MAXINTERFACES=16;
char *ip=NULL;
int fd, intrface;
struct ifreq buf[MAXINTERFACES]; ///if.h
struct ifconf ifc; ///if.h

if ((fd = socket (AF_INET, SOCK_DGRAM, 0)) >= 0) //socket.h
{
ifc.ifc_len = sizeof buf;
ifc.ifc_buf = (caddr_t) buf;
if (!ioctl (fd, SIOCGIFCONF, (char *) &ifc)) //ioctl.h
{
intrface = ifc.ifc_len / sizeof (struct ifreq);

while (intrface-->0)
{
if (!(ioctl (fd, SIOCGIFADDR, (char *) &buf[intrface])))
{
ip=(inet_ntoa(((struct sockaddr_in*)(&buf[intrface].ifr_addr))->sin_addr));//types
break;
}
}
}
close (fd);
}
return ip;
}

获取本地主机ip

标签:

原文地址:http://www.cnblogs.com/sou1boy/p/4536600.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!