Archive

Posts Tagged ‘nss’

gethostbyname3 & gethostbyname4

April 22nd, 2010 1 comment

I was queried recently about the semi-mysterious and undocumented gethostbyname3_r() and gethostbyname4_r() functions within glibc, and noticed that there’s little googleable available on the topic.

A quick summary: These functions are getaddrinfo() backends – they are not available as public functions for users (though you can do similar tricks as nscd does if you really want to get at them) and they are further extensions of the gethostbyname2_r() function. If you want to use their functionality, just use appropriate getaddrinfo() incanations.
The functions are provided by the appropriate NSS backends and not all backends might provide them.

gethostbyname3_r() also retrieves TTL and canonical hostname (another hidden interface getcanonname_r() also does that) information for the host in single step.

gethostbyname4_r() is much more interesting. First, it does not return hostents but a more extended gaih_addrtuple format (see <nss.h>) that is more akin to struct addrinfo. Even more importantly, the lookup is not limited to a particular address family but returns information for all available AFs.

This means that AF_UNSPEC lookup does not need to call gethostbyname3_r() for AF_INET and then AF_INET6, but the gethostbyname4_r() NSS backend can do the lookup for both at once – in case of /etc/hosts the file is scanned once while in case of DNS both DNS requests are dispatched in parallel instead of in sequence. (…which can lead to infamous strange problems with some cheap DSL routers that will just ignore one of the queries and all queries will start to hang – this is why Debian has (had?) disabled gethostbyname4_r().)

In case you need to use the functions for some reason, glibc:nscd/ai_cache.c is simpler usage example than getaddrinfo() source.

Categories: linux, software Tags: , ,