用iptables做端口转发

Forwarding Traffic with IPTables on CentOS 6

Introduction

Welcome! In this tutorial, I’ll explain how to forward TCP/UDP traffic to a new server. This can especially be useful when you’re migrating your Vultr VPS to a new location. This tutorial covers both 32 and 64 bit versions of CentOS 6.

Install IPTables

Before we can start, IPTables must be installed. Install IPTables with the following command.

yum install iptables -y

Enable routing

Packet forwarding must be enabled on your server for this method to work. Open the file /etc/sysctl.conf. Make sure the following line is enabled, and set to “1”:

net.ipv4.ip_forward = 1

Save the file, then run:

sysctl -p

Configure IPTables

Step One

Perform the commands below accordingly to your needs. Change “2.2.2.2” to your new server’s IP address and “venet0” to your Ethernet adapter. Also, change “80:90” to the desired port range that will be forwarded.

iptables -A FORWARD -d 2.2.2.2 -i venet0 -p tcp -m tcp --dport 80:90 -j ACCEPT

If you want to forward a single port, simply replace the port range above with a single port. To forward UDP instead, replace instances of “tcp” above with “udp”.

Step Two

Add routes for your newly added rules. Rules refer to the directives inside of IPTables. In this example, “1.1.1.1” represents your old server’s IP address and like before, “2.2.2.2” represents the destination/new server’s IP. Again, update the port range and TCP/UDP strings as needed.

iptables -t nat -A PREROUTING -d 1.1.1.1 -p tcp -m tcp --dport 80:90 -j DNAT --to-destination 2.2.2.2

Step Three

Finalize the NAT forwarding. Change “venet0” to your Ethernet adapter.

iptables -t nat -A POSTROUTING -o venet0 -j MASQUERADE

Step Four

Save our newly added rules and soft-restart IPTables.

service iptables save
service iptables reload

From: https://www.vultr.com/docs/forwarding-traffic-with-iptables-on-centos-6

另外,可参考:
https://www.centos.org/docs/4/html/rhel-sg-en-4/s1-firewall-ipt-fwd.html

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Time limit is exhausted. Please reload CAPTCHA.