如何获取我的服务器应用程序的 IPv4 地址?
How do I get the IPv4 address of my server application?
即使翻阅了很多相关帖子,我似乎也找不到合适的答案。我有一个 winsock2 应用程序(服务器设置代码根据我的需要从 the microsoft documentation 进行了调整),我只想在绑定后显示服务器 IPv4 地址。 这是我目前的代码(绑定到 ListenSocket 后放置):
char ipv4[80];
sockaddr_in inaddr;
int len = sizeof(inaddr);
int error = getsockname(m_ListenSocket, (sockaddr*)&inaddr, &len);
const char* p = inet_ntop(AF_INET, &inaddr.sin_addr, ipv4, 80);
std::cout << "Server address: " << ipv4 << std::endl;
然而,这将 return“0.0.0.0”。如果我将 inet_ntop
与 struct addrinfo* result
一起使用(请参阅上面的链接文档),我会得到一个以“2.xxx.xxx.xxx”开头的 IP,而我知道我的本地地址是“192.168.1.18”。在上面的代码中,error
是 0 而 inet_ntop 的结果不是 NULL
。
如何让实际 IP 地址显示出来?
示例代码来自 Microsoft
#include <iostream>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iphlpapi.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
// Link with Iphlpapi.lib
#pragma comment(lib,"IPHLPAPI.lib")
#pragma comment(lib,"Ws2_32.lib")
const unsigned int WORKING_BUFFER_SIZE = 15 * 1024;
void displayAddress(const SOCKET_ADDRESS &Address)
{
// cout << "\n Length of sockaddr: " << Address.iSockaddrLength;
if (Address.lpSockaddr->sa_family == AF_INET)
{
sockaddr_in *si = (sockaddr_in *)(Address.lpSockaddr);
char a[INET_ADDRSTRLEN] = {};
if (inet_ntop(AF_INET, &(si->sin_addr), a, sizeof(a)))
cout << "\n IPv4 address: " << a;
}
else if (Address.lpSockaddr->sa_family == AF_INET6)
{
sockaddr_in6 *si = (sockaddr_in6 *)(Address.lpSockaddr);
char a[INET6_ADDRSTRLEN] = {};
if (inet_ntop(AF_INET6, &(si->sin6_addr), a, sizeof(a)))
cout << "\n IPv6 address: " << a;
}
}
int main(){
DWORD dwSize = 0;
DWORD dwRetVal = 0;
ULONG outBufLen = WORKING_BUFFER_SIZE;
ULONG flags = GAA_FLAG_INCLUDE_PREFIX;
PIP_ADAPTER_ADDRESSES pAddresses = NULL;
PIP_ADAPTER_ADDRESSES pCurrAddresses = NULL;
pAddresses = (IP_ADAPTER_ADDRESSES *) malloc(WORKING_BUFFER_SIZE);
dwRetVal = GetAdaptersAddresses(AF_INET, flags, NULL, pAddresses, &outBufLen);
if (dwRetVal == ERROR_BUFFER_OVERFLOW) {
free(pAddresses);
cout << "Buffer error!" << endl;
return -1;
}
pCurrAddresses = pAddresses;
while (pCurrAddresses) {
for (PIP_ADAPTER_UNICAST_ADDRESS pu = pCurrAddresses->FirstUnicastAddress; pu != NULL; pu = pu->Next)
displayAddress(pu->Address);
pCurrAddresses = pCurrAddresses->Next;
}
free(pAddresses);
cout << endl;
return 0;
}