我有一个分配给它的5个IP地址的接口(作为虚拟适配器),我们称它们为x1,x2,x3,x4和x5。
目前我有SNAT POSTROUTING转发规则从本地源范围到特定的公共IP地址。 以下是当前规则的一个例子:
-A POSTROUTING -s 10.8.0.0/24 -j SNAT --to-source x1.x1.x1.x1
我想实现的是,新build立的本地连接将被路由后分配给(x1 / x2 / x3 / x4 / x5)上面的IP之一,随机/循环。 我厌倦了在网上寻找解决scheme,但我没有find任何有关如何这样做的信息。 我几乎可以肯定,这是可行的。
iptables有一个统计模块,可以使用。 它可以以随机或确定的两种模式运行。 这是你的规则如何写入该模块。
确定性版本:
-A POSTROUTING -s 10.8.0.0/24 -m statistic --mode nth --every 5 --packet 0 -j SNAT --to-source 192.0.2.1 -A POSTROUTING -s 10.8.0.0/24 -m statistic --mode nth --every 4 --packet 0 -j SNAT --to-source 192.0.2.2 -A POSTROUTING -s 10.8.0.0/24 -m statistic --mode nth --every 3 --packet 0 -j SNAT --to-source 192.0.2.3 -A POSTROUTING -s 10.8.0.0/24 -m statistic --mode nth --every 2 --packet 0 -j SNAT --to-source 192.0.2.4 -A POSTROUTING -s 10.8.0.0/24 -j SNAT --to-source 192.0.2.5
随机版本:
-A POSTROUTING -s 10.8.0.0/24 -m statistic --mode random --probability 0.2 -j SNAT --to-source 192.0.2.1 -A POSTROUTING -s 10.8.0.0/24 -m statistic --mode random --probability 0.25 -j SNAT --to-source 192.0.2.2 -A POSTROUTING -s 10.8.0.0/24 -m statistic --mode random --probability 0.3333333333 -j SNAT --to-source 192.0.2.3 -A POSTROUTING -s 10.8.0.0/24 -m statistic --mode random --probability 0.5 -j SNAT --to-source 192.0.2.4 -A POSTROUTING -s 10.8.0.0/24 -j SNAT --to-source 192.0.2.5
要清楚的是,这不是负载平衡。 负载平衡将平衡多个主机上的负载。 你只在同一主机上的多个IP上传播源地址。 这不会给你任何性能好处,但使你的设置更复杂。
但是,假设你想继续。
根据iptables-extensions手册页。
SAME (IPv4-specific) Similar to SNAT/DNAT depending on chain: it takes a range of addresses (`--to 1.2.3.4-1.2.3.7') and gives a client the same source-/destination-address for each connection. NB: The DNAT target's --persistent option replaced the SAME target. --to ipaddr[-ipaddr] Addresses to map source to. May be specified more than once for multiple ranges. --nodst Don't use the destination-ip in the calculations when selecting the new source-ip --random Port mapping will be forcibly randomized to avoid attacks based on port prediction (kernel >= 2.6.21).
但显然范围必须是线性的。 例如1.2.3.4-1.2.3.7 = 1.2.3.4,1.2.3.5,1.2.3.6,1.2.3.7我不确定是否符合您的设置。
但是,如果这样做,你可以做:
-A POSTROUTING -s 10.8.0.0/24 -j SAME --to x1.x1.x1.x1-x5.x5.x5.x5 --nodst
–nodst选项应该使它更随机一些,select哪个源IP,我不知道它是使用循环法还是简单的随机化。