獲取本機地址信息,遇到小問題...有待解決

程序代碼:spa

 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.hcode

而後百度說,本身弄個頭文件就行:blog

 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 但這個方法很差使:get

而後繼續編譯,說是缺乏win32.lib...非常奇怪it

相關文章
相關標籤/搜索