How to Prioritize IPv4 over IPv6 in Linux

In some cases - especially when dealing with unstable IPv6 connections or services that lack proper IPv6 support - you may want to make Linux prefer IPv4 by default, even if IPv6 is enabled. Instead of disabling IPv6 entirely (which may cause unintended side effects), a better approach is to configure address selection priorities using the gai.conf
file.
What is gai.conf?
The /etc/gai.conf
file controls how the system prioritizes IP addresses when multiple options are returned by DNS. It affects the behavior of the getaddrinfo()
system call, which is used by most Linux applications - including apt
, curl
, ssh
, git
, and others.
Configuring IPv4 Priority
Open the
gai.conf
file with superuser privileges:sudo vi /etc/gai.conf
Find the following line:
# precedence ::ffff:0:0/96 100
Uncomment it by removing the leading
#
:precedence ::ffff:0:0/96 100
Save and close the file.
How This Works
- The prefix
::ffff:0:0/96
represents IPv4-mapped IPv6 addresses, used internally by the system for handling IPv4 traffic. - The value
100
gives these addresses a high selection priority. - As a result, when both IPv6 (AAAA) and IPv4 (A) DNS records are available for a hostname, the system will prefer the IPv4 address.
Verifying the Configuration
Run:
getent ahosts google.com
If the first result is an IPv4 address, the configuration is working.
Additional Notes
- The change takes effect immediately; no reboot is required.
- This method works on all major Linux distributions that use
glibc
andgetaddrinfo()
(including Ubuntu, Debian, Arch, Fedora, and others). - It is a safe and compliant solution that does not interfere with IPv6 functionality or routing, and does not require disabling any subsystems.