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 220.127.116.11, 18.104.22.168 and 22.214.171.124
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.
Let’s talk about a real example
Yahoo.com has these IP addresses when I was typing this post:
126.96.36.199, 188.8.131.52, 184.108.40.206, 220.127.116.11, 18.104.22.168, 22.214.171.124
Let’s say, you want to go to Yahoo.com through its 126.96.36.199/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:188.8.131.52/120 3
scopev4 ::ffff:184.108.40.206/120 2
scopev4 ::ffff:220.127.116.11/120 1
Second column is the IP subnet, third column is the priority. The lower number has high priority.
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 (18.104.22.168) 56(84) bytes of data.