How To Choose a Specific IP Address From a DNS Result?

As you probably know, you call getaddrinfo when you make a DNS request in a Linux/Unix based operating system.

Some domains have multiple A records. Let’s say you make a DNS request for example.com, and you get 2.2.2.2, 3.3.3.3 and 4.4.4.4

There may be lots of different scenarios to choose one of those IP addresses in real life.

Since we are living in the cloud age, most services don’t have this kind of static IP assignments.

You may want to use only one subnet of those 3 different subnets. Because of some routing issues, some DNS load balancing issues etc.

Photo by Jordan Harrison on Unsplash

Let’s talk about a real example

Yahoo.com has these IP addresses when I was typing this post:

74.6.231.20, 74.6.143.26, 74.6.143.25, 98.137.11.164, 98.137.11.163, 74.6.231.21

Let’s say, you want to go to Yahoo.com through its 74.6.143.0/24 subnet.

You can make some configurations in iptables. However, I’d like to point out another solution, which is easier than iptables configurations.

There is a file, which is called /etc/gai.conf.

Gai.conf is a configuration file for getaddrinfo function. You can choose the destination IP address/subnet through gai.conf

I’m going to add these lines to my /etc/gai.conf:

scopev4 ::ffff:98.137.11.0/120 3
scopev4 ::ffff:74.6.231.0/120 2
scopev4 ::ffff:74.6.143.0/120 1

getaddrinfo will decide which IP address/subnet is going to be used. It is going to be calculated through the 3rd column.

The workflow is going to be like this:

1) Call getaddrinfo
2) Get IP address of yahoo.com
3) Check if there is a rule for these IP addresses in the gai.conf file
4) Get the one that has high priority. If an IP address of yahoo.com is not listed in gai.conf and getaddrinfo would return that IP.

You can test your configuration like this:

root@adil:~# systemd-resolve --flush-caches && ping yahoo.com -c1PING yahoo.com (74.6.143.25) 56(84) bytes of data.