[C++]使用GetAdaptersAddresses API取得本地IP
GetAdaptersAddresses(AF_UNSPEC, 0, NULL, NULL, &outBufLen);
GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_SKIP_ANYCAST, NULL, pAddresses, &outBufLen);
pCurrAddresses = pAddresses;
while (pCurrAddresses)
{
if(pCurrAddresses->OperStatus != IfOperStatusUp)
{
pCurrAddresses = pCurrAddresses->Next;
continue;
}
pUnicast = pCurrAddresses->FirstUnicastAddress;
while (pUnicast)
{
addr = pUnicast->Address.lpSockaddr;
ZeroMemory(buff, bufflen);
if (addr->sa_family == AF_INET6)
{
sockaddr_in6 *sa_in6 = (sockaddr_in6 *)addr;
inet_ntop(AF_INET6, &(sa_in6->sin6_addr), buff, bufflen);
}else
{
sockaddr_in *sa_in = (sockaddr_in *)addr;
inet_ntop(AF_INET, &(sa_in->sin_addr), buff, bufflen);
}
localIPs.push_back(buff);
pUnicast = pUnicast->Next;
}
pCurrAddresses = pCurrAddresses->Next;
}
free(pAddresses);
...</pre>
#include “stdafx.h”
#include <winsock2.h>
#include <WS2tcpip.h>
#include <iphlpapi.h>
#include <vector>
#include <string>
#include <algorithm>
// Link with Iphlpapi.lib #pragma comment(lib, “Ws2_32.lib”) #pragma comment(lib, “IPHLPAPI.lib”)
using namespace std;
vector<string> GetLocalIPs()
{
vector<string> localIPs;
PIP_ADAPTER_ADDRESSES pAddresses = NULL;
ULONG outBufLen = 0;
GetAdaptersAddresses(AF_UNSPEC, 0, NULL, pAddresses, &outBufLen);
pAddresses = (IP_ADAPTER_ADDRESSES*) malloc(outBufLen);
if (GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_SKIP_ANYCAST, NULL, pAddresses, &outBufLen) != NO_ERROR)
{
free(pAddresses);
return localIPs;
}
char buff[100];
DWORD bufflen=100;
PIP_ADAPTER_ADDRESSES pCurrAddresses = NULL;
PIP_ADAPTER_UNICAST_ADDRESS pUnicast = NULL;
LPSOCKADDR addr = NULL;
pCurrAddresses = pAddresses;
while (pCurrAddresses)
{
if(pCurrAddresses->OperStatus != IfOperStatusUp)
{
pCurrAddresses = pCurrAddresses->Next;
continue;
}
pUnicast = pCurrAddresses->FirstUnicastAddress;
while (pUnicast)
{
addr = pUnicast->Address.lpSockaddr;
ZeroMemory(buff, bufflen);
if (addr->sa_family == AF_INET6)
{
sockaddr_in6 *sa_in6 = (sockaddr_in6 *)addr;
inet_ntop(AF_INET6, &(sa_in6->sin6_addr), buff, bufflen);
}else
{
sockaddr_in *sa_in = (sockaddr_in *)addr;
inet_ntop(AF_INET, &(sa_in->sin_addr), buff, bufflen);
}
localIPs.push_back(buff);
pUnicast = pUnicast->Next;
}
pCurrAddresses = pCurrAddresses->Next;
}
free(pAddresses);
return localIPs;
}
int _tmain(int argc, _TCHAR* argv[]) { vector<string> localIPs = GetLocalIPs(); for_each (localIPs.begin(), localIPs.end(), [&](string ip) { char szTmp[255]; sprintf(szTmp, “%s “, ip.c_str()); printf(szTmp); }); return 0; }