Как включить/выключить IP Forwarding в Linux
Почти во всех распространенных дистрибутивах IP Forwarding выключен по-умолчанию и это имеет смысл, так как далеко не каждый его использует. Но в том случае, если вы планируете поднять собственный маршрутизатор на ОС Linux, настроить VPN сервер и так далее, вам необходимо включить форвардинг пакетов (маршрутизацию транзитных IP-пакетов, т.е. тех пакетов, которые не предназначены именно для вашего компьютера) в вашей ОС. В данной мини-инструкции я расскажу как это можно сделать:
Проверяем включен или нет IP Forwarding в данный момент
Для проверки в каком состоянии в данный момент находится форвардинг пакетов (включен или выключен), мы должны сделать запрос к ядру через команду sysctl. Делается это так:
В ответ мы получим текущий статус (1 — включен, 0 — выключен)
Временно включаем/отключаем IP Forwarding
Чтобы включить форвардинг пакетов «на лету» и не перезагружать систему, нам достаточно выполнить следующую команду:
Чтобы выключить форвардинг пакетов «на лету» и не перезагружать систему, нам достаточно выполнить следующую команду:
Постоянно включаем/отключаем IP Forwarding в системе
В том случае, если нам необходимо перманентно включить или отключить форвардинг пакетов в системе, нам необходимо внести правки в конфигурационный файл /etc/sysctl.conf
Для перманентного включения IP Forwarding, в конец данного файла добавляем следующую строчку:
Для перманентного отключения IP Forwarding, в конец данного файла добавляем следующую строчку:
. И сохраняем отредактированный файл.
Далее, чтобы применить новую настройку, которую мы добавили, нам необходимо выполнить следующую команду:
Как включить IP Forwarding в Linux
Хотите превратить ваш компьютер в маршрутизатор или интернет-шлюз? Первым делом, вы должны включить пересылку IP-пакетов (IP Forwarding).
Если вы хотите превратить ваш компьютер в маршрутизатор или интернет-шлюз (а может быть даже и в VPN-сервер!), вам необходимо включить IP forwarding, который позволит перенаправлять IP-пакеты с одного сетевого интерфейса на другой.
По умолчанию, в большинстве дистрибутивов Linux, IP forwarding отключен.
Перед тем, как его включать, необходимо убедиться в его текущем состоянии — включен он или выключен?.
Откроем Терминал и выполним в командной строке следующую команду:
sudo cat /proc/sys/net/ipv4/ip_forward
Если результатом ее выполнения явилась цифра 1, появившаяся на экране, это означает, что IP forwarding у вас включен и вам ничего предпринимать не нужно.
Если на экране появилась цифра 0, то это означает, что IP forwarding отключен в вашей системе. Приступим к его включению.
Включение IP forwarding.
Для того, чтобы включить пересылку IP-пакетов (IP forwarding) необходимо перейти в режим суперпользователя root (выполнив в консоли команду sudo bash и введя верный пароль). Далее необходимо выполнить любую из представленных ниже команд:
sudo sysctl -w net.ipv4.ip_forward=1 или echo 1 > /proc/sys/net/ipv4/ip_forward
После выполнения одной из этих команд, IP forwarding в вашей системе будет включен и IP-пакеты будут пересылаться с одного сетевого интерфейса на другой.
Для того, чтобы после запуска системы, IP forwarding включался автоматически, откройте в своем любимом текстовом редакторе файл /etc/sysctl.conf, отыщите там строку, начинающуюся с net.ipv4.ip_forward и придайте ей вид:
Выйдите из редактора с сохранением файла, затем выполните в командной строке команду: sudo sysctl -p /etc/sysctl.conf (это позволит применить сделанные нами изменения без перезапуска системы).
Все! При включенном IP forwarding, IP-пакеты должны у вас активно «бегать», а пользователи радоваться появившемуся у них Интернету.
How to enable IP Forwarding in Linux
By default any modern Linux distributions will have IP Forwarding disabled. This is normally a good idea, as most peoples will not need IP Forwarding, but if we are setting up a Linux router/gateway or maybe a VPN server (pptp or ipsec) or just a plain dial-in server then we will need to enable forwarding. This can be done in several ways that I will present bellow.
Check if IP Forwarding is enabled
We have to query the sysctl kernel value net.ipv4.ip_forward to see if forwarding is enabled or not: Using sysctl:
or just checking out the value in the /proc system:
As we can see in both the above examples this was disabled (as show by the value 0).
Enable IP Forwarding on the fly
As with any sysctl kernel parameters we can change the value of net.ipv4.ip_forward on the fly (without rebooting the system):
the setting is changed instantly; the result will not be preserved after rebooting the system.
Permanent setting using /etc/sysctl.conf
If we want to make this configuration permanent the best way to do it is using the file /etc/sysctl.conf where we can add a line containing net.ipv4.ip_forward = 1
if you already have an entry net.ipv4.ip_forward with the value 0 you can change that 1.
To enable the changes made in sysctl.conf you will need to run the command:
On RedHat based systems this is also enabled when restarting the network service:
and on Debian/Ubuntu systems this can be also done restarting the procps service:
Using distribution specific init scripts
Although the methods presented above should work just fine and you would not need any other method of doing this, I just wanted to note that there are also other methods to enable IP Forwarding specific to some Linux distributions. For example Debian based distributions might use the setting:
set it to yes and restart the network service. Also RedHat distributions might set this using:
and again restart the network service.
Regardless the method you have used once you have completed this you can check it out using the same method shown above:
If the result is 1 then the Linux system will start forwarding IP packets even if they are not destined to any of its own network interfaces.
ps. I was setting up a VPN dial-in server when I wrote this post ;-).
How to Enable IP Forwarding Under Ubuntu/Linux Mint
In this tutorial, we will see how to enable IP Forwarding under Ubuntu/Linux Mint. IP Forwarding is required when users want to make their computers act as a router, gateway, DMZ, VPN server, and it is also used in internet connection sharing.
Getting Started
To check whether IP Forwarding is enabled or not, you can use this command:
If it is disabled, you will get this output:
Enabling IP Forwarding Temporarily
To enable IP Forwarding temporarily, run these commands:
Re-check again the status of IP Forwarding with this command:
If it is enabled, you will get this output:
However, IP Forwarding will be disabled once you reboot your system. For a permanent configuration, see below.
Enabling IP Forwarding Permanently
Open the terminal and edit the /etc/sysctl.conf file with this command:
Search and uncomment this line:
Save your file and exit, then run this command:
Enabling IP-Forwarding for IPv4 in Debian GNU/Linux
The term IP Forwarding describes sending a network package from one network interface to another one on the same device. It should be enabled when you want your system to act as a router that transfers IP packets from one network to another.
On a Linux system the Linux kernel has a variable named `ip_forward` that keeps this value. It is accessible using the file `/proc/sys/net/ipv4/ip_forward`. The default value is 0 which means no IP Forwarding, because a regular user who runs a single computer without further components is not in need of that, usually. In contrast, for routers, gateways and VPN servers it is quite an essential feature.
Next, we will explain to you how to enable IP Forwarding temporarily, and permanently.
IP Forwarding As A Temporary Solution
In order to enable this kernel parameter on the fly you have two options. Option 1 simply stores the value of 1 in the variable from above as follows:
Option 2 uses the `sysctl` command that allows you to adjust different kernel parameters at runtime, too [2]. As an administrative user run the following command:
Keep in mind that this setting is changed instantly. Also, the result will not be preserved after rebooting the system.
You can query the stored value as follows:
This command returns a value of 0 for no IP Forwarding, and a value of 1 for IP Forwarding enabled. As an alternative, using `sysctl` also shows you the current status:
Enabling IP Forwarding Permanently
In order to achieve this some other steps have to be done. First, edit the file `/etc/sysctl.conf`. Search for a line containing the entry “#net.ipv4.ip_forward=1”, and remove the # at the beginning of the line.
Then, save the file, and run the `sysctl` command in order to enable the adjusted settings:
The option `-p` is short for `–load`, and requires a name for the configuration file to be followed.
Next, restart the proc file system that provides information about the status of the Linux kernel using the following command:
In about 2015 the file name was shortened from `procps.sh` to `procps`. So, on elderly Debian systems the script that you have to invoke is named `procps.sh`, instead.
Dealing With Systemd
The next hurdle came with the release of Systemd version 221. IP Forwarding is disabled by default, and enabling requires an additional file to be there. If it is not there yet, just add it. The file name consists of the name of the network interface followed by the suffix `.network`, for example `eth0.network` for the network interface `/dev/eth0`. As stated in the documentation [4], other extensions are ignored.
The following code snippet shows the setup for the network interface `/dev/tun0`. It contains of two sections — `Match` and `Network`. In the Match section define the name of the network interface, and in the network section enable IP Forwarding.
Conclusion
Activating IP Forwarding for IPv4 is not a mystery. Just a few steps, and your are there. Happy hacking!