Linux server uses firewall iptables policy for port hopping
Forwarded by two different servers
Open the function of port forwarding
First, enable the IP forwarding function, which is disabled by default.
Temporary modification:
[root@localhost ~] # echo 1 > / proc/sys/net/ipv4/ip_forward
It takes effect immediately after the modification, but reverts to the default value of 0 if the system is rebooted.
Permanent modification:
Vi / etc/sysctl.conf
# find the following value and change 0 to 1
Net.ipv4.ip_forward = 1
# sysctl-p (make it effective immediately)
The default value of 0 is to disable ip forwarding. If you change it to 1, you can enable ip forwarding.
Configure port forwarding
Suppose the user accesses 115.29.112.119virtual 8804 and I want it to be forwarded to 42.99.16.84plu8890
First, port 8804 should be opened on the server.
Modify the configuration file: vim / etc/sysconfig/iptables
-An INPUT-p tcp-m state-- state NEW-m tcp-- dport 8804-j ACCEPT
Or the command line executes and saves
[root@localhost sysconfig] # iptables-An INPUT-p tcp-m state-- state NEW-m tcp-- dport 8804-j ACCEPT [root@localhost sysconfig] # service iptables saveiptables: Saving firewall rules to / etc/sysconfig/iptables: [OK]
Port forwarding
Method 1: command line execution
It needs to be saved, otherwise it will only take effect immediately, and the firewall rule will be emptied if it has been restarted.
Iptables-t nat-A PREROUTING-d 115.29.112.119-p tcp-- dport 8804-j DNAT-- to-destination 42.99.16.84 tcp 8890
Iptables-t nat-A POSTROUTING-d 42.99.16.84-p tcp-- dport 8890-j SNAT-- to-source 115.29.112.119
Command that is saved without changing the configuration file: service iptables save
Method 2: save directly to the configuration file
Modify / etc/sysconfig/iptables configuration file to add rules
-A PREROUTING-d 115.29.112.119-p tcp-- dport 8804-j DNAT-- to-destination 42.99.16.84 DNAT 8890
-A POSTROUTING-d 42.99.16.84-p tcp-- dport 8890-j SNAT-- to-source 115.29.112.119
After configuring the restart firewall:
1.systemctl restart iptables (centos7); 2.service iptables restart (previous version of centos7)
View configured policies
Iptables-t nat-- list-- line-numbers
Native port forwarding
If you only need to forward between different ports of this machine, it will be easier. For example, to access http://ip:8888, I want to return the content of http://ip:6666. The configuration is as follows:
[root@localhost] # iptables-t nat-A PREROUTING-p tcp-- dport 8888-j REDIRECT-- to-ports 6666 [root@localhost ~] # service iptables save [root@localhost ~] # service iptables restart