Turning off ipv6 linux

How to disable IPv6 on Linux

Question: I notice that one of my applications is trying to establish a connection over IPv6. But since our local network is not able to route IPv6 traffic, the IPv6 connection times out, and the application falls back to IPv4, which causes unnecessary delay. As I don’t have any need for IPv6 at the moment, I would like to disable IPv6 on my Linux box. What is a proper way to turn off IPv6 on Linux?

IPv6 has been introduced as a replacement of IPv4, the traditional 32-bit address space used in the Internet, to solve the imminent exhaustion of available IPv4 address space. However, since IPv4 has been used by every host or device connected to the Internet, it is practically impossible to switch every one of them to IPv6 overnight. Numerous IPv4 to IPv6 transition mechanisms (e.g., dual IP stack, tunneling, proxying) have been proposed to facilitate the adoption of IPv6, and many applications are being rewritten, as we speak, to add support for IPv6. One thing for sure is that IPv4 and IPv6 will inevitably coexist for the forseeable future.

Ideally the ongoing IPv6 transition process should not be visible to end users, but the mixed IPv4/IPv6 environment might sometimes cause you to encounter various hiccups originating from unintended interaction between IPv4 and IPv6. For example, you may experience timeouts from applications such as apt-get or ssh trying to unsuccessfully connecting via IPv6, DNS server accidentally dropping AAAA DNS records for IPv6, or your IPv6-capable device not compatible with your ISP’s legacy IPv4 network, etc.

Of course this doesn’t mean that you should blindly disable IPv6 on you Linux box. With all the benefits promised by IPv6 (e.g., more efficient routing, simpler network configuration), we as a society want to fully embrace it eventually, but as part of troubleshooting process for end-user experienced hiccups, you may try turning off IPv6 to see if indeed IPv6 is a culprit.

Here are a few techniques allowing you to disable IPv6 partially (e.g., for a certain network interface) or completely on Linux. These tips should be applicable to all major Linux distributions including Ubuntu, Debian, Linux Mint, CentOS, Fedora, RHEL, and Arch Linux.

Читайте также:  Linux image file information

Check if IPv6 is Enabled on Linux

All modern Linux distributions have IPv6 automatically enabled by default. To see IPv6 is activated on your Linux, use ifconfig or ip commands. If you see inet6 in the output of these commands, this means your Linux has IPv6 enabled.

Disable IPv6 Temporarily

If you want to turn off IPv6 temporarily on your Linux system, you can use /proc file system. By temporarily, I mean that the change you make to disable IPv6 will not be preserved across reboots. IPv6 will be enabled back again after you reboot your Linux box.

To disable IPv6 for a particular network interface, use the following command.

$ sudo sh -c 'echo 1 > /proc/sys/net/ipv6/conf//disable_ipv6'

For example, to disable IPv6 for eth0 interface:

$ sudo sh -c 'echo 1 > /proc/sys/net/ipv6/conf/eth0/disable_ipv6'

To re-enable IPv6 back on eth0 interface:

$ sudo sh -c 'echo 0 > /proc/sys/net/ipv6/conf/eth0/disable_ipv6'

If you want to disable IPv6 system-wide for all interfaces including loopback interface, use this command:

$ sudo sh -c 'echo 1 > /proc/sys/net/ipv6/conf/all/disable_ipv6'

Disable IPv6 Permanently across Reboots

The above method does not permanently disable IPv6 across reboots. IPv6 will be activated again once you reboot your system. If you want to turn off IPv6 for good, there are several ways you can do it.

Method One

The first method is to apply the above /proc changes persistently in /etc/sysctl.conf file. That is, open /etc/sysctl.conf with a text editor, and add the following lines.

# to disable IPv6 on all interfaces system wide net.ipv6.conf.all.disable_ipv6 = 1 # to disable IPv6 on a specific interface (e.g., eth0, lo) net.ipv6.conf.lo.disable_ipv6 = 1 net.ipv6.conf.eth0.disable_ipv6 = 1

To activate these changes in /etc/sysctl.conf , run:

$ sudo sysctl -p /etc/sysctl.conf

Method Two

An alternative way to disable IPv6 permanently is to pass a necessary kernel parameter via GRUB/GRUB2 during boot time.

Open /etc/default/grub with a text editor, and add ipv6.disable=1 to GRUB_CMDLINE_LINUX variable.

GRUB_CMDLINE_LINUX="xxxxx ipv6.disable=1"

In the above, xxxxx denotes any existing kernel parameter(s). Add ipv6.disable=1 after them.

Finally, don’t forget to apply the modified GRUB/GRUB2 settings by running:

On Debian, Ubuntu or Linux Mint:

$ sudo grub2-mkconfig -o /boot/grub2/grub.cfg

Now IPv6 will be completely disabled once you reboot your Linux system.

Other Optional Steps after Disabling IPv6

Here are a few optional steps you can consider after disabling IPv6. This is because while you disable IPv6 in the kernel, other programs may still try to use IPv6. In most cases, such application behaviors will not break things, but you want to disable IPv6 for them for efficiency or safety reason.

Читайте также:  Acer как установить linux

1. /etc/hosts

Depending on your setup, /etc/hosts may contain one or more IPv6 hosts and their addresses. Open /etc/hosts with a text editor, and comment out all lines which contain IPv6 hosts.

# comment these IPv6 hosts # ::1 ip6-localhost ip6-loopback # fe00::0 ip6-localnet # ff00::0 ip6-mcastprefix # ff02::1 ip6-allnodes # ff02::2 ip6-allrouters

2. Network Manager

If you are using Network Manager to manage your network settings, you can disable IPv6 on Network Manager as follows. On Network Manager, open the wired connection for which you want to disable IPv6, click on IPv6 Settings tab, and choose Ignore in Method field. Save the change and exit.

3. SSH server

By default, OpenSSH server ( sshd ) tries to bind on both IPv4 and IPv6 addresses. To force sshd to bind only on IPv4 address, open /etc/ssh/sshd_config with a text editor, and add the following line. inet is for IPv4 only, and inet6 is for IPv6 only.

$ sudo vi /etc/ssh/sshd_config

Support Xmodulo

This website is made possible by minimal ads and your gracious donation via PayPal or credit card

Please note that this article is published by Xmodulo.com under a Creative Commons Attribution-ShareAlike 3.0 Unported License. If you would like to use the whole or any part of this article, you need to cite this web page at Xmodulo.com as the original source.

Источник

Вики IT-KB

Относительно IPv6 есть такой тезис «Включенный и ненастроенный протокол IPv6 хуже, чем выключенный протокол IPv6». Если использование IPv6 не планируется, то можно выключить поддержку IPv6 глобально на уровне системы.

Убедимся в том, что в системе действительно присутствуют IPv6 интерфейсы:

Также можно увидеть, что некоторые приложения имеют активные TCP-прослушиватели на интерфейсах IPv6. Посмотреть все прослушиваемые в системе порты можно командой:

Чтобы выключить поддержку IPv6 на всех сетевых интерфейсах сразу, открываем на редактирование файл sysctl.conf

В конец файла добавляем строки:

# Turn off IPv6 # net.ipv6.conf.all.disable_ipv6 = 1 net.ipv6.conf.default.disable_ipv6 = 1 net.ipv6.conf.lo.disable_ipv6 = 1 net.ipv6.conf.eth0.disable_ipv6 = 1

Для выключения IPv6 на всех интерфейсах системы достаточно параметра net.ipv6.conf.all.disable_ipv6 . Прочие параметры указаны в качестве примера отключения на уровне отдельных интерфейсов. При этом, если необходимо, изменяем имя сетевого интерфейса eth0 на тот, который используется у нас.

Читайте также:  Laptops that work with linux

Для вступления изменений в силу, заставим sysctl перечитать файл /etc/sysctl.conf :

Cнова проверяем список интерфейсов, где IPv6 интерфейсов уже не должно остаться:

Дополнительные источники информации:

Проверено на следующих конфигурациях:

Версия ОС
Debian GNU/Linux Stretch 9.2.1
Debian GNU/Linux Buster 10.0
Debian GNU/Linux Bullseye 11.2
Debian GNU/Linux Bookworm 12.0

Автор первичной редакции:
Алексей Максимов
Время публикации: 25.11.2017 11:33

Обсуждение

На дебиан 10, в котором настройка сетевой карты проведена через gui (advanced network manager) такой способ не прокатывает, и отключение в самом графическом интерфейсе не проходит.

Алексей Максимов , 14.12.2019 18:49

Описанное здесь было проверено на Debian Buster без графического интерфейса, и в таком случае это работает. Систем подобного класса с графическим интерфейсом не имеем, поэтому прокомментировать это никак не смогу.

Откуда в buster такое именование сетевых интерфейсов? Зачем перезагружать сервер, если достаточно сервис перезапустить?

Отлично работает, за исключением ошибки
bash: sysctl: command not found
так как в чистом дебиане 10 не настроено окружение на
/sbin
Решением будет использовать
/sbin/sysctl -p
заместо
/sbin
Благодарю автора за эту заметку, сервера теперь нормально и быстро обновляются. Пива и мяса в ваш дом.

Зачем каждый интерфейс указывать, если первой строкой (net.ipv6.conf.all.disable_ipv6 = 1) стоит отключение ipv6 на всех интерфейсах?

Алексей Максимов , 09.06.2023 17:25

Это больше для наглядности. Что отключить можно не только глобально, но и на уровне отдельного интерфейса.

unix-linux/debian/how-to-turn-off-ipv6-in-debian-linux.txt · Последнее изменение: 20.06.2023 14:16 — Алексей Максимов

Источник

Как отключить IP версии 6 в Linux

Обновлено

Обновлено: 16.05.2020 Опубликовано: 23.03.2019

IPv6 далеко не всегда может использоваться в системе. Более того, он может вызвать некоторые проблемы при обращении к локальной петле (127.0.0.1) — запросы могут пойти на адрес ::1, что может привести к тому, что некоторые приложения будут работать не корректно.

В данной инструкции используются универсальные методы, которые подойдут для различных систем, например, Ubuntu, CentOS, Debian, Red Hat и так далее.

Отключение через ядро Linux

Быстрее всего отключить IPv6 через настройку ядра. Это универсальный способ и он подойдет для многих дистрибутивов на базе Linux.

Глобально (для всех интерфейсов)

Создаем или открываем файл:

* 99-sysctl.conf является основным конфигурационным файлом, а 10-ipv6-privacy.conf в каталоге sysctl.d — дополнительным. Для удобства лучше использовать последний.

Добавляем следующие строки:

net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1

Если вносили изменения в файл /etc/sysctl.d/99-sysctl.conf:

Если вносили изменения в файл /etc/sysctl.d/10-ipv6-privacy.conf:

sysctl -p /etc/sysctl.d/10-ipv6-privacy.conf

Проверяем — должны остаться только адреса IPv4:

Для определенного интерфейса

Если нужно отключить IPv6 только для одного интерфейса, например, для eth0, также открываем настройку ядра.

Источник

Оцените статью
Adblock
detector