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 ?
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