Home > OS >  How do I get the IPv4 address of my server application?
How do I get the IPv4 address of my server application?

Time:11-11

Even after sifting through many related posts I can't seem to find a suitable answer. I have a winsock2 application (code for server setup is adapted for my needs from the microsoft documentation) and I simply want to display the server IPv4 address after binding. This is the code I have so far (placed after binding to the 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;

However this will return "0.0.0.0". If I use inet_ntop with struct addrinfo* result (see linked documentation above) I get an IP starting with "2.xxx.xxx.xxx", while I know my local address is "192.168.1.18". In the code above, error is 0 and the result of inet_ntop is not NULL. How does one get the actual IP address to show up?

CodePudding user response:

Example code from 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;
}
  • Related