VC6下验证OK,各种切换网卡都可以,断网后是localhost(127.0.0.1)
#include <stdio.h>
#include <winsock.h>
#include <winsock2.h>//编译不通过,各种错误
#pragma comment(lib,"ws2_32.lib")
void CheckIP(void)
{
WSADATA wsaData;
char name[155];
char *ip;
PHOSTENT hostinfo;
if ( WSAStartup( MAKEWORD(2,0), &wsaData ) == 0 )
{
if( gethostname ( name, sizeof(name)) == 0)
{
if((hostinfo = gethostbyname(name)) != NULL)
{ //这些就是获得IP的函数
ip = inet_ntoa (*(struct in_addr *)*hostinfo->h_addr_list);
printf("%s\n",ip);
}
}
WSACleanup( );
}
}
转自网易博客: http://blog.163.com/wxjfish_85/blog/static/474548472007822103231773/