C++獲取本機的ip地址程序
#include <WinSock2.h> #pragma comment(lib,"ws2_32") //鏈接到ws2_32動態鏈接庫class CInitSock { public:CInitSock(BYTE minorVer = 2,BYTE majorVer = 2){WSADATA wsaData;WORD VersionRequset;VersionRequset = MAKEWORD(minorVer,majorVer);//裝載winsock庫if (WSAStartup(VersionRequset,&wsaData)!=0){//裝載winsock庫失敗,推出exit(0);}}~CInitSock(){WSACleanup();} };
上面是頭文件
#include <iostream> #include "a.h" using namespace std; CInitSock Initsock; bool GetIp(); int main() {GetIp();return 0; } bool GetIp() {char szText[256];//獲取本機主機名稱int iRet;iRet = gethostname(szText,256);int a = WSAGetLastError();if (iRet!=0){printf("gethostname() Failed!");return FALSE;}//通過主機名獲取到地址信息HOSTENT *host = gethostbyname(szText);if (NULL==host){printf("gethostbyname() Failed!");return false;}in_addr PcAddr;for (int i=0;;i++){char *p = host->h_addr_list[i];if (NULL==p){break;}memcpy(&(PcAddr.S_un.S_addr),p,host->h_length);char*szIP = ::inet_ntoa(PcAddr);printf("本機的ip地址是:%s\n",szIP);}system("pause"); }
源代碼文件
posted on 2018-01-16 11:40 秦瑞It行程實錄 閱讀(...) 評論(...) 編輯 收藏