'Binding getaddrinfo to particular interface (source IP)

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?



Solution 1:[1]

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.

Solution 2:[2]

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

Solution 3:[3]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 dbush
Solution 2 Community
Solution 3 msundius