代码如下:
#include "stdafx.h"
#include <WinSock2.h>
int get_local_ip() {
WSADATA wsaData;
if(WSAStartup(MAKEWORD(2,2),&wsaData))
{
return -1;
}
char hostname[128];
int ret = gethostname(hostname, sizeof(hostname));
if (ret == -1) {
return -1;
}
struct hostent *hent;
hent = gethostbyname(hostname);
if (NULL == hent) {
return -1;
}
//直接取h_addr_list列表中的第一个地址h_addr
char ip[128];
sprintf_s(ip, "%s", inet_ntoa(*((struct in_addr *)hent->h_addr)));
printf("%s
", ip);
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
get_local_ip();
system( "PAUSE ");
return 0;
}
注意:
以上程序我使用vs2015编写的,需要在属性中的添加库ws2_32.lib