獲取本機IP
阿新 • • 發佈:2020-08-07
1 // ConsoleApplication12.cpp : This file contains the 'main' function. Program execution begins and ends there. 2 // 3 #include <winsock2.h> 4 #include <windows.h> 5 #include <WS2tcpip.h> 6 #include <IPTypes.h> 7 #include <iphlpapi.h> 8 #include <iostream> 910 #pragma comment(lib, "ws2_32.lib") 11 #pragma comment(lib, "IPHLPAPI.lib") 12 13 using namespace std; 14 15 16 17 void get_local_ip() 18 { 19 ULONG rCode = 0; 20 ULONG Length = sizeof(IP_ADAPTER_INFO); 21 std::string IpAddr; 22 23 PIP_ADAPTER_INFO pIpAdapterInfo = newIP_ADAPTER_INFO(); 24 25 rCode = GetAdaptersInfo(pIpAdapterInfo, &Length); 26 27 if (ERROR_BUFFER_OVERFLOW == rCode) { 28 //重新申請記憶體空間用來儲存所有網絡卡資訊 29 delete pIpAdapterInfo; 30 pIpAdapterInfo = (PIP_ADAPTER_INFO)new BYTE[Length]; 31 rCode = GetAdaptersInfo(pIpAdapterInfo, &Length); 32} 33 if (rCode == ERROR_SUCCESS) { 34 //返回第一張網絡卡的第一個IP地址 35 for (UINT i = 0; i < 16; i++) { 36 if (!pIpAdapterInfo->IpAddressList.IpAddress.String[i]) 37 break; 38 39 IpAddr += pIpAdapterInfo->IpAddressList.IpAddress.String[i]; 40 41 } 42 } 43 if (pIpAdapterInfo) { 44 delete pIpAdapterInfo; 45 } 46 cout << IpAddr.c_str() << endl; 47 //return IpAddr; 48 } 49 50 51 int main() 52 { 53 get_local_ip(); 54 //cout << ip.c_str() << endl; 55 std::cout << "Hello World!\n" << endl; 56 getchar(); 57 } 58