GPT答: |
7i24.cn
|
//方法一:
#include <windows.h>
#include <winsock2.h>
#include <iphlpapi.h>
#include <stdio.h>
#include <string>
#pragma comment(lib, "IPHLPAPI.lib")
std::string getIPAddress()
{
std::string ret;
PIP_ADAPTER_INFO pAdapterInfo;
PIP_ADAPTER_INFO pAdapter = NULL;
DWORD dwRetVal = 0;
UINT i;
ULONG ulOutBufLen = sizeof(IP_ADAPTER_INFO);
pAdapterInfo = (IP_ADAPTER_INFO *)malloc(sizeof(IP_ADAPTER_INFO));
if (pAdapterInfo == NULL) {
return "";
}
if (GetAdaptersInfo(pAdapterInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW) {
free(pAdapterInfo);
pAdapterInfo = (IP_ADAPTER_INFO *)malloc(ulOutBufLen);
if (pAdapterInfo == NULL) {
_endthread();
return "";
}
}
if ((dwRetVal = GetAdaptersInfo(pAdapterInfo, &ulOutBufLen)) == NO_ERROR) {
pAdapter = pAdapterInfo;
while (pAdapter) {
if (pAdapter->Type != MIB_IF_TYPE_ETHERNET) {
pAdapter = pAdapter->Next;
continue;
}
IP_ADDR_STRING *pIpAddrStr = &(pAdapter->IpAddressList);
do {
if (strcmp(pIpAddrStr->IpAddress.String, "0.0.0.0") != 0) {
std::string ipStr(pIpAddrStr->IpAddress.String);
if(ipStr.find("169.254") != std::string::npos) {
pIpAddrStr = pIpAddrStr->Next;
continue;
}
ret = ipStr;
break;
}
pIpAddrStr = pIpAddrStr->Next;
} while (pIpAddrStr);
if (!ret.empty())
break;
pAdapter = pAdapter->Next;
}
free(pAdapterInfo);
}
return ret;
}
//方法二
#include<WinSock2.h>
#include<WS2tcpip.h>
#include<Iphlpapi.h>
#include<Windows.h>
#include<string>
std::string getLocalIP()
{
char szHostName[255] = {0};
char szLocalIP[255] = {0};
gethostname(szHostName, sizeof(szHostName));
HOSTENT *host;
host = gethostbyname(szHostName);
for(int i = 0; host->h_addr_list[i]; i++)
{
inet_ntop(AF_INET, host->h_addr_list[i], szLocalIP, sizeof(szLocalIP));
std::string ipStr = szLocalIP;
if(ipStr.find("169.254") != std::string::npos) {
continue;
}
return ipStr;
}
return 0;
}
|