iptables实现内外网ip转换

准备三台虚拟机

内网访问外网

网络设置为仅主机(关闭DHCP功能)

设置一台双网卡机器充当iptables服务器

设置一台内网机

设置一台外网机,下载并开启httpd服务

在iptables服务器上设置iptables

在/etc/sysctl.conf中添加net.ipv4.ip_forward=1

[root@iptables etc]# sysctl -p
net.ipv4.ip_forward = 1
加载配置

内网访问外网,内网IP不能再公网出现,所以要将内网IP转换成外网IP。

iptables -t nat -A POSTROUTING -p tcp -s 192.168.100.100 -o ens36 -j SNAT --to 12.12.100.10

[root@iptables network-scripts]# iptables -t nat -A POSTROUTING -p tcp -s 192.168.100.100 -o ens36 -j SNAT --to 12.12.100.10
[root@iptables network-scripts]# iptables -t nat -nvL
Chain PREROUTING (policy ACCEPT 16 packets, 1580 bytes)
 pkts bytes target     prot opt in     out     source               destination         

Chain INPUT (policy ACCEPT 2 packets, 644 bytes)
 pkts bytes target     prot opt in     out     source               destination         

Chain OUTPUT (policy ACCEPT 4 packets, 269 bytes)
 pkts bytes target     prot opt in     out     source               destination         

Chain POSTROUTING (policy ACCEPT 4 packets, 269 bytes)
 pkts bytes target     prot opt in     out     source               destination         
   11   730 RETURN     all  --  *      *       192.168.122.0/24     224.0.0.0/24        
    0     0 RETURN     all  --  *      *       192.168.122.0/24     255.255.255.255     
    0     0 MASQUERADE  tcp  --  *      *       192.168.122.0/24    !192.168.122.0/24     masq ports: 1024-65535
    0     0 MASQUERADE  udp  --  *      *       192.168.122.0/24    !192.168.122.0/24     masq ports: 1024-65535
    0     0 MASQUERADE  all  --  *      *       192.168.122.0/24    !192.168.122.0/24    
    0     0 SNAT       tcp  --  *      ens36   192.168.100.100      0.0.0.0/0            to:12.12.100.10

在iptables服务器上抓包

在内网机访问

结束抓包

查看抓包结果

外网访问内网

iptables服务器不变

将另外两台IP互换

iptables服务器中的/etc/sysctl.conf已经添加net.ipv4.ip_forward=1

外网想访问内网,需要将目的地址转换为内网地址。

iptables -t nat -A PREROUTING -p tcp -d 12.12.100.10 --dport 8080 -i

[root@iptables sl01]# iptables -t nat -F
[root@iptables sl01]# iptables -t nat -A PREROUTING -p tcp -d 12.12.100.10 --dport 8080 -i ens36 -j DNAT --to 192.168.100.100:80
[root@iptables sl01]# iptables -t nat  -nL
Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination         
DNAT       tcp  --  0.0.0.0/0            12.12.100.10         tcp dpt:8080 to:192.168.100.100:80

Chain INPUT (policy ACCEPT)
target     prot opt source               destination         

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination         

Chain POSTROUTING (policy ACCEPT)
target     prot opt source               destination 

在iptables服务器上抓包

在外网机远程访问

查看抓包结果

实验完成

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值