利用iptables配置Minecraft跳板机

发布于 2020-01-14  1996 次阅读


Introduction

Servers

搬瓦工的 CN2 GT 服务器 S1(2g 2core)

CN2 GIA 服务器 S2(0.5g 1core)

阿里云服务器 S3

need

我拥有三台服务器,其中需要使用 S1 开服,但是由于线路原因,游戏丢包情况十分严重,相比之下配置较低的 cn2 gia 服务器就拥有很优质的线路,且 S2 还不够,仍然会有少许丢包,导致mc掉线,故再加上阿里云服务器 S3 进行中转,通过利用 S2S3 作为跳板机对流量进行中转,便可以达到较佳的游戏体验。

graph

mc客户端 <------> 阿里云 S3 <------> cn2 gia 服务器 S2 <------> mc服务器 S1

Configuration

参考资料:nat-with-iptables

ip_forward

服务器的流量转发功能默认关闭,需要手动开启

sudo sysctl net.ipv4.ip_forward # CentOS or Ubuntu

net.ipv4.ip_forward = 0 #表明未开启流量转发

sudo echo "net.ipv4.ip_forward = 1"|sudo tee /etc/sysctl.d/99-ipforward.conf
net.ipv4.ip_forward = 1 
# CentOS

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

便可以开启转发,但重启后会恢复,我们需要将其写入配置

sudo sysctl -p /etc/sysctl.d/99-ipforward.conf
# CentOS

sudo sysctl -p
# Ubuntu

net.ipv4.ip_forward = 1 # 写入配置

iptables

install & start

  1. 对于 Ubuntu 系统,自带 iptables
  2. 对于 CentOS 系统,默认安装了 firewall ,需要先将 firewall 关闭,再安装 iptables

参考此文章:centos如何开启iptables

systemctl stop firewalld.service # 停止firewall
systemctl disable firewalld.service # 禁止firewall开机启动

# yum -y install iptables-services 安装iptables(有的系统不需安装,视情况而定)
service iptables start # 启动iptables

Configuration

sudo iptables -F
sudo iptables -t nat -F
# 清除iptables原有的配置文件

流量转发配置

自行替换 Gateway_IPGateway_PortDest_IPDest_Port

分别对应 跳板机的ip和端口,目标机器的ip和端口

这里的协议我设置为了 tcp, 根据你需要转发的协议类型进行设置

sudo iptables -t nat -A PREROUTING -p tcp --dport Gateway_Port -j DNAT --to-destination Dest_IP:Dest_PORT # 将进入跳板机的流量转发到目标ip

sudo iptables -t nat -A POSTROUTING -p tcp -d Dest_IP --dport Dest_Port -j SNAT --to-source Gateway_ip # 将目标ip返回的流量转发给原ip

sudo iptables -t nat -L -n # 查看iptables配置情况

查看配置无误之后,即完成

若希望保存配置

service iptables save
# CentOS

sudo iptables-save | sudo tee /etc/iptables.up.rules
# Ubuntu

iptables: Saving firewall rules to /etc/sysconfig/iptables:[ OK ]

Q&A

1. 阿里云无法转发

阿里云采用了 弹性ip 的技术, 即在你访问其公网ip之后又经过一层nat,转发到内网

所以我们的 iptables 配置也应该将本机ip修改为内网ip

这时我们的 Gateway_IP 应该填写内网ip, 即 172 . 17. . (具体请自行查询)

[root@izuf6eyc1ac8d7lj4j6q2oz /]# ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 172.17.*.*  netmask 255.255.192.0  broadcast 172.17.*.*
        ether 00:16:3e:10:91:52  txqueuelen 1000  (Ethernet)
        RX packets 3528831  bytes 368948380 (351.8 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 3485951  bytes 321121112 (306.2 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        loop  txqueuelen 1  (Local Loopback)
        RX packets 6260  bytes 392377 (383.1 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 6260  bytes 392377 (383.1 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

2. 多层跳板如何搭建

多层跳板,就是将跳板机 src目的地址 设置为下级跳板 dest ,层层中转即可

即配置 S1 、 S2

  1. 使 S3 中转给 S2

  2. 使 S2 中转给 S1


CTFer|NOIPer|CSGO|摸鱼|菜鸡