54

I know that I can enable IP forward by echoing 1 to /proc/sys/net/ipv4/ip_forward, but how can I make this permanent?

By the way I want another method rather than start up scripts, is there any?

Eric Carvalho
  • 54,385
Hojat Taheri
  • 5,409

3 Answers3

78

Edit /etc/sysctl.conf and search for the following lines:

# Uncomment the next line to enable packet forwarding for IPv4
#net.ipv4.ip_forward=1

Uncomment net.ipv4.ip_forward=1:

# Uncomment the next line to enable packet forwarding for IPv4
net.ipv4.ip_forward=1

Or in one line command :

sudo sysctl -w net.ipv4.ip_forward=1
boly38
  • 223
Eric Carvalho
  • 54,385
24

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

/etc/sysctl.conf:
net.ipv4.ip_forward = 1

If you already have an entry net.ipv4.ip_forward with the value 0 you can change that to 1.

To enable the changes made in sysctl.conf you will need to run the command:

sudo sysctl -p /etc/sysctl.conf

On RedHat based systems this is also enabled when restarting the network service:

service network restart

and on Debian/Ubuntu systems this can be also done restarting the procps service:

sudo /etc/init.d/procps restart

Source: How to Enable IP Forwarding in Linux

guntbert
  • 13,134
Meintjes
  • 2,420
  • 1
  • 15
  • 21
5

If you need to enable it in script you can use commands below to enable

sed -i 's/#net.ipv4.ip_forward=1/net.ipv4.ip_forward=1/' /etc/sysctl.conf
sysctl -p

or disable:

sed -i 's/net.ipv4.ip_forward=1/net.ipv4.ip_forward=0/' /etc/sysctl.conf
sysctl -p
ilya
  • 49
  • I think there is a typo in the command line to enable: the idea is changing the value 0 for 1 so it should be: ed -i 's/#net.ipv4.ip_forward=0/net.ipv4.ip_forward=1/' /etc/sysctl.conf sysctl -p – Pablo Adames Dec 14 '22 at 02:20
  • No. Enabling command just remove "#" in the beginning. So there is no typo – ilya Mar 24 '23 at 20:58
  • ilya, you are correct, I will take back my comment. I missed that the target was to remove the # alone. Instead, I thought of matching an uncommented line with the disabled setting of 0 to change it to the enabled value of 1. – Pablo Adames Mar 30 '23 at 06:28
  • @ilya yes but disabling them should add back the "#" and not putting value 0, since if you have to reenable again it will not do it... – EAK TEAM Feb 03 '24 at 18:33