clinuxnetwork-programmingdnsuclibc

Alternative to gethostbyname where I can choose the DNS server?


I need to resolve some hostnames from my application. Is there any alternative to gethostbyname where I can give as a parameter my own DNS server to use as a resolver?

I have already coded my own function, but I thought there may be one I don't know about.

I am using Linux/C language. My libc is uclibc. But I am also curious about GNU LibC.

Thanks.


Solution

  • You'll need to do your own query, but it isn't difficult.

    To do this, you would want to use the res_query() family of functions, which allow you to specify the resolver through an environmental variable:

    The res_init() function reads the configuration files (see resolv.conf(5)) to get the default domain name, search order and name server address(es). If no server is given, the local host is tried. If no domain is given, that associated with the local host is used. It can be overridden with the environment variable LOCALDOMAIN

    IBM's docs go a little more in depth with how to set the variable:

    The configured search list (struct state.defdname and struct state.dnsrch) can be overridden by setting the environment variable LOCALDOMAIN to a space-separated list of up to 6 search domains with a total of 256 characters (including spaces). If a search list is specified, the default local domain is not used on queries.

    Notes -

    These functions have the additional benefit of being able to retrieve more detailed data (MX, etc) as well. Still, if you have something smaller that works equally well, there's no sense in not using it.