通过windows API获取本机IP
1 //获取本机ip 2 CString getIP() 3 { 4 SOCKET sd = WSASocket(AF_INET, SOCK_DGRAM, 0, 0, 0, 0); 5 CString strIP; 6 7 if (sd == SOCKET_ERROR) 8 { 9 closesocket(sd); 10 return _T(""); 11 } 12 else 13 { 14 INTERFACE_INFO InterfaceList[20]; 15 unsigned long nBytesReturned; 16 17 if (WSAIoctl(sd, SIO_GET_INTERFACE_LIST, 0, 0, &InterfaceList, sizeof(InterfaceList), &nBytesReturned, 0, 0) == SOCKET_ERROR) 18 { 19 closesocket(sd); 20 return _T(""); 21 } 22 else 23 { 24 int nNumInterfaces = nBytesReturned / sizeof(INTERFACE_INFO); 25 26 for (int i = 0; i < nNumInterfaces; i++) 27 { 28 sockaddr_in* pAddress; 29 pAddress = (sockaddr_in*)&(InterfaceList[i].iiAddress); 30 strIP = inet_ntoa(pAddress->sin_addr); 31 if (strIP == _T("127.0.0.1")) 32 { 33 continue; 34 } 35 else 36 { 37 closesocket(sd); 38 return strIP; 39 } 40 } 41 closesocket(sd); 42 return _T(""); 43 } 44 } 45 }
记得包含头文件
1 #include <WinSock2.h> 2 #include <WS2tcpip.h>
参考自 https://bbs.csdn.net/topics/360237856