1 #define WIN32_LEAN_AND_MEAN 2 #include <iostream> 3 #include <fstream> 4 #include <windows.h> 5 #include <winsock2.h> 6 #include <string> 7 #include <Ws2tcpip.h> 8 using namespace std; 9 10 #pragma comment(lib,"ws2_32.lib") 11 12 int main() 13 { 14 WSADATA wsaData; 15 WSAStartup(MAKEWORD(2,2),&wsaData); 16 addrinfo *addr=NULL; 17 char szhostname[128]; 18 char szLocalip[20]; 19 20 gethostname(szhostname,sizeof(szhostname)); 21 22 getaddrinfo(szhostname,NULL,NULL,&addr); 23 in_addr ipaddr=(((sockaddr_in*)(addr->ai_addr))->sin_addr); 24 strcpy(szLocalip,inet_ntoa(ipaddr)); 25 cout<<szLocalip<<endl; 41 WSACleanup(); 42 system("pause"); 43 return 0; 44 }
在默认windows.h会包含winsock.h,当你包含winsock2.h就会冲突,因此在包含windows.h前需要定义一个宏,去除winsock.h