获取本地主机ip

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;
}

posted on 2015-05-28 18:08  sou1boy  阅读(171)  评论(0)    收藏  举报

导航