以下代码的参考网上找的资料,具体哪个网页记不清了。希望对其他人有用。
需要:
#include "winsock2.h"
#pragma comment( lib, "ws2_32" )
代码如下:
CString GetHostIp()
{
char szHostName[128];
const char* pszAddr = NULL;
struct hostent * pHost;
int i;
WSADATA wsaData;
CString str;
CString ipStr = "";
WSAStartup(0x202, &wsaData );
if( gethostname(szHostName, 128) == 0 )
{
pHost = gethostbyname(szHostName);
for( i = 0; pHost!= NULL && pHost->h_addr_list[i]!= NULL; i++ )
{
/*对每一个IP地址进行处理*/
pszAddr = inet_ntoa (*(struct in_addr *)pHost->h_addr_list[i]);
str = pszAddr;
str = str.Left(3);
//不能是192 和 127 开头的
if (str != "192" && str != "127")
{
ipStr = pszAddr;
break;
}
else
{
ipStr = pszAddr;
}
}
}
WSACleanup();
return ipStr;
}