Skip to contentSkip to conversation

intended behavior of REDIRECT

DISCUSSION Luke Elliott 2 participants 2 messages Apr 15, 2008 – Apr 25, 2008

lore
Share & tools
lore
#0 lore raw

Hi

I'm trying to figure out the intended behavior of a REDIRECT rule such as:

iptables -t nat -A PREROUTING -p tcp --dport 9002 -j REDIRECT --to-ports 9003-9004

I'd like to balance connections to port 9002 across the two servers on ports 9003 and 9004. Using the --random (or --random 1 with iptables 1.3.8...) option works, but what should the non-random rule actually do?

Digging around in the 2.6.24 kernel it seems to boil down to tcp_unique_tuple() in nf_nat_proto_tcp.c. The interesting bit:

static u_int16_t port;

...

   for (i = 0; i < range_size; i++, port++) {
       *portptr = htons(min + port % range_size);
       if (!nf_nat_used_tuple(tuple, ct))
           return 1;
   }

So if I'm reading this correctly, _port_ will only get incremented once an in use tuple is hit. And assuming there are no other rules in place, that means only after 64K-ish connections from a single host to port 9002? This seems to be what I see in practice - "everything" gets forwarded to port 9003 (though TBH I've only tried a few hundred connections).

So presumably the intention is not to round-robin connections, something like:

   for (i = 0; i < range_size; i++) {
       *portptr = htons(min + port % range_size);
       ++port;
       if (!nf_nat_used_tuple(tuple, ct))
           return 1;
   }

(Though no doubt that breaks lots of other usages of the function...)

An insight gratefully received!

Regards

Luke Elliott.

#1 lore raw
Quoted 7 lines · Luke Elliott

iptables -t nat -A PREROUTING -p tcp --dport 9002 -j REDIRECT --to-ports 9003-9004

I'd like to balance connections to port 9002 across the two servers on ports 9003 and 9004. Using the --random (or --random 1 with iptables 1.3.8...) option works, but what should the non-random rule actually do?

I'd rather use the two rules:
1. -m statistic --mode nth --every 2 -j REDIRECT --to-port 9003 +
2. (unconditional) -j REDIRECT --to-port 9004

Which will reliably RR over the ports.