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

2 min readFeb 4, 2021

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, and you get, and

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 has these IP addresses when I was typing this post:,,,,,

Let’s say, you want to go to through its 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: 3
scopev4 ::ffff: 2
scopev4 ::ffff: 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
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 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 -c1PING ( 56(84) bytes of data.