首页 > 代码库 > 获取本机地址信息,遇到小问题...有待解决

获取本机地址信息,遇到小问题...有待解决

程序代码:

技术分享
 1 #include "../common/InitSock.h"
 2 #include <stdio.h>
 3 CInitSock initSock;
 4 void main()
 5 {
 6     char szHost[256];
 7     ::gethostname(szHost,256);
 8     hostent *pHost = ::gethostbyname(szHost);
 9     in_addr addr;
10     for(int i =0;;i++)
11     {
12         char *p = pHost->h_addr_list[i];
13         if(p == NULL)
14             break;
15         memcpy(&addr.S_un.S_addr, p, pHost->h_length);
16         char *szIp = ::inet_ntoa(addr);
17         printf("本地IP地址:%s \n",szIp);
18     }
19 }
技术分享

第一次编译说 找不到 ../common/InitSock.h

然后百度说,自己弄个头文件就行:

技术分享
 1 #include  <winsock2.h> 
 2 #pragma comment(lib, "WS2_32 ")
 3 #pragma comment(lib, "ws2.lib ")    //   链接到WS2_32.lib 
 4 class   CInitSock    
 5 { 
 6     public: 
 7     CInitSock(BYTE   minorVer   =   2,   BYTE   majorVer   =   2) 
 8     { 
 9         //   初始化WS2_32.dll 
10         WSADATA   wsaData; 
11         WORD   sockVersion   =   MAKEWORD(minorVer,   majorVer); 
12         if(::WSAStartup(sockVersion,   &wsaData)   !=   0) 
13         { 
14             exit(0); 
15         } 
16     } 
17 
18     ~CInitSock() 
19     {    
20         ::WSACleanup();    
21     } 
22 }; 
技术分享

然后保存成:initsock.h 但这个方法不好使:

然后继续编译,说是缺少win32.lib...很是奇怪

获取本机地址信息,遇到小问题...有待解决