Using getaddrinfo() to retrieve local IP addresses
Yann Droneaud
ydroneaud@opteya.com
Mon Oct 7 08:48:00 GMT 2019
Hi,
Le vendredi 04 octobre 2019 à 18:36 -0700, Brendan Shanks a écrit :
>
> Traditionally, passing the local hostname (i.e. returned from
> gethostname()) to getaddrinfo() returns the hostâs IP addresses,
> suitable for binding to.
>
This is assuming NSS database (likely /etc/hosts) to be filled with
valid data.
> However, some Linux distributions (Debian, Ubuntu, Arch, likely
> others) define the local hostname to â127.0.1.1â in /etc/hosts. (
> https://www.debian.org/doc/manuals/debian-reference/ch05.en.html#_the_hostname_resolution
> )
> In this case, getaddrinfo() only returns â127.0.1.1â.
>
That's probably a workaround for some broken configuration when machine
hostname is set to some name not present in NSS database, and not
resolvable through DNS: resolving the name will take some amount of
time until it timeout.
Having a default entry that resolve to loopback will cut the resolution
time.
> On these systems, is there a flag or an alternate ânodeâ name that
> can be passed to getaddrinfo() that will result in all the hostâs IP
> addresses rather than just the useless â127.0.1.1â?
>
I'm not aware of such feature.
> For background, Iâm working on fixing a Wine bug (
> https://bugs.winehq.org/show_bug.cgi?id=46940) where a Windows game
> uses this method to get the local network IP address. Wineâs
> getaddrinfo() implementation largely passes through to the host
> getaddrinfo(), and the game tries to use â127.0.1.1â for local
> network sockets. Iâll have to add a special case to Wineâs
> getaddrinfo() for the local hostname, but it would be much simpler to
> use the host getaddrinfo()âs list of IP addresses rather than having
> to use netlink. getifaddrs() is close to being correct, but it
> includes loopback addresses, deprecated IPv6 temporary addresses,
> etc.
>
It's quite difficult to identify the "local network IP address" from
hostname, as,
- a device can have multiple network interface,
- each interface can have multiple addresses, in different family.
- interface goes up, down
- addresses are added, removed
- a device can only have a single hostname
- this hostname can be a valid, resolvable DNS address, mDNS address,
/etc/hosts entry, or not.
You probably have to look for freedesktop API, NetworkManager, or
systemd, for some hints.
Regards.
--
Yann Droneaud
OPTEYA
More information about the Libc-help
mailing list