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:

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:

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:

You can test your configuration like this:

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store