Search code examples
cposix

Is there a POSIX-compliant way of getting local network IP address of my computer?


I know this question has been asked a million times in one form or another, but no question gave me a POSIX-compliant way of doing it.

I need to get the local network address of my computer without using getifaddrs or any other non POSIX-compliant way of accessing interfaces. Is that possible ?


Solution

  • There is no direct support for such a thing but you can use udp sockets (SOCK_DGRAM) to connect to a known distant address. Since udp sockets are stateless this doesn't do any network traffic.

    Then you can query for the local endpoint of that socket (getsockname) to obtain the local IP adress through which your system would route. Again since udp is stateless this just queries your local routing tables and no real network traffic is issued.

    Don't forget to close the socket after that.

    Remote public nameservers are good for that purpose. You can test for several of them

    • one of them might occasionally be down or there might be no route for some reason to that part of the world
    • your process may be on the same local network as the server and you might only obtain some special local address
    • test for IPv4 and IPv6 addresses