1 #include <stdio.h> 2 #include <WinSock2.h> 3 #pragma comment(lib, "ws2_32.lib") 4 5 int main(int argc, char **argv) 6 { 7 WSADATA wsaData; 8 WORD wVersion = MAKEWORD(2, 2); 9 if(::WSAStartup(wVersion, &wsaData) != 0) //初始化套接字库 10 { 11 printf("Initialize the socket failed\n"); 12 return 0; 13 } 14 15 char szHostName[256]; 16 ::gethostname(szHostName, sizeof(szHostName)); //获取主机名 17 printf("主机名:%s\n", szHostName); 18 19 hostent *pHost = ::gethostbyname(szHostName); //通过主机名获取IP 20 21 //打印出所有的IP地址 22 in_addr addr; 23 for(int i = 0; ; i++) 24 { 25 char *p = pHost->h_addr_list[i]; 26 if(p == NULL) 27 break; 28 29 memcpy(&addr.S_un.S_addr, p, pHost->h_length); 30 char *szIp = ::inet_ntoa(addr); 31 32 printf("本机IP地址:%s\n", szIp); 33 } 34 35 return 0; 36 }