I use getaddrinfo() to get IP Address corresponding to a server using a URL. It essentially sends DNS query to the DNS server. I want to be able to send that query from a particular outbound interface. Basically I have multiple interfaces through which DNS query could be sent out. Currently, getaddrinfo() doesn't have a way to dictate which interface it should use to send out the DNS query. Is the only option to change getaddrinfo() routine? Does anyone know of any other way to achieve this?
-
1This seems to be more an issue of the name resolver and the network stack (routing) than anything you should be dealing with in your program code. Why is it even an issue in the first place? – John Bollinger Oct 28 '16 at 18:31
3 Answers
The fundamental issue with the question is that you seem to expect getaddrinfo
to work with DNS only, and then to be able to fine-tune the specifics of that DNS lookup. However, that is not what it does - it will use all name-resolving facilities on the system, which typically means it will do a hosts
file lookup, and whatever else is configured in nsswitch.conf
, which is usually DNS. For some of these non-DNS lookups, a source address binding may not make any sense, so it's not part of the least-common-denominator interface.
If you know that for your specific purpose you will never need the response of a name lookup from anywhere other than DNS, then you can use a DNS-specific function instead, one that will enable you to do this kind of fine-tuning.
There are several examples of DNS C libraries listed at gethostbyname dual network interfaces, select which one to use

- 1
- 1

- 725
- 6
- 13
The interface chosen to access a given IP address is dictated by the routing tables.
Since you presumably have the IP of the DNS server, it will be accessed by whatever interface the routing table says to use for that IP address, regardless of which application sends the request.
You would need to modify the routing table to force traffic over a particular interface. If it's only the DNS server that should use a fixed interface, you would add a route for that specific IP to the routing table for the interface you want.
On Linux, you can modify the routing table via the ip route
command line tool.

- 205,898
- 23
- 218
- 273
-
Thanks dbush. Yes, but in my case I have a multi-path default route over multiple interfaces (mostly 2 or more). I would like to send dns query out of each of these interfaces but need to control which query is using interface A vs interface N. Hence the need to control, which source interface to pick while calling getaddrinfo(). I checked the hints arguments, but doesn't seem like there is an option – caliuser Oct 28 '16 at 19:00
rfc 3484 details an algorithm of which source addr (i.e. interface) to use when none is specified, but this works I think only for ipv6... see /etc/gai.conf

- 79
- 3