WORD wVersionRequested;
WSADATA wsaData;
char name[255];
CString ip;
// LPCSTR ip;
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);
printf("当前IP:%s",ip);
printf("\n当前主机名:%s",name);
}
WSACleanup( );
}
编译的时候,应将ws2_32.lib输入到object/library modyles中,因为socket定义都在ws2_32.lib中.
完整程序实现:
#i nclude<stdio.h>
#i nclude<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( );
} }
int main(void)
{
CheckIP();
return 0;
}