Q: IPTables Load Balancing with Sticky Session (IP Affinity) I been scouring IPTables module documentation on ideas how I can achieve load distribution with source IP session state affinity.  Lets clarify, I am not load balancing, simply distributing packets matching my NAT Chain to local listening ports.  Once a packet is redirected to a port I'd like this state to stick for n minutes before its connection is no longer tracked and moves to the next probability rule etc...
My current state:
/sbin/iptables -t nat -A REDSOCKS -p tcp -m statistic --mode random --probability .10 -j REDIRECT --to-ports 10001
/sbin/iptables -t nat -A REDSOCKS -p tcp -m statistic --mode random --probability .10 -j REDIRECT --to-ports 10002
/sbin/iptables -t nat -A REDSOCKS -p tcp -m statistic --mode random --probability .10 -j REDIRECT --to-ports 10003
/sbin/iptables -t nat -A REDSOCKS -p tcp -m statistic --mode random --probability .10 -j REDIRECT --to-ports 10004
/sbin/iptables -t nat -A REDSOCKS -p tcp -m statistic --mode random --probability .10 -j REDIRECT --to-ports 10005
/sbin/iptables -t nat -A REDSOCKS -p tcp -m statistic --mode random --probability .10 -j REDIRECT --to-ports 10006
/sbin/iptables -t nat -A REDSOCKS -p tcp -m statistic --mode random --probability .10 -j REDIRECT --to-ports 10007
/sbin/iptables -t nat -A REDSOCKS -p tcp -m statistic --mode random --probability .10 -j REDIRECT --to-ports 10008
/sbin/iptables -t nat -A REDSOCKS -p tcp -m statistic --mode random --probability .10 -j REDIRECT --to-ports 10009
/sbin/iptables -t nat -A REDSOCKS -p tcp -j REDIRECT --to-ports 10010


A: Hi let me one partial answer/ note:
as the rules are evaluated in sequence and not parallel your distribution is not what you suppose.
Each line is 10% but not from the same base. So 1st line is "real" 10%, but second line is 10% from the rest (90%), so technically it is "only" 9%. 3rd line is 10% but from the rest (81%) so it is "only 8.1% etc.
Distribution for 10 ports would be:
0.1
0.11
0.13
0.14
0.17
0.2
0.25
0.33
0.5
1

Last one mean all the rest so your "last" line ;-).

A: Here is the piece of bash to make those rules properly:
rules=10
calc() { bc -l <<< "scale=3; $@"; }
for ((i = rules ; i >= 1 ; i--)); do
  echo /sbin/iptables -t nat -A REDSOCKS -p tcp -m statistic --mode random --probability $(calc 1/$i) -j REDIRECT --to-ports $(calc 10001+$rules-$i)
done

