views:

247

answers:

4

Hi

I have a TCP server that is listening on a particular interface only. I want that after the accept() call if the incoming connection was from xxx.xxx.xxx.0 subnet then the data should go through intf1 otherwise the data should be sent through intf2 which is where my server is listening.

Both the interfaces have the same route settings and priority. All the networks are accessible from both the interfaces.

One way out could be to add a new route through intf1 with higher priority, but I want this to be a code based decision.

The code is in pure C written on Linux.

Thanks for the help.

A: 

Unfortunately your options are limited, as the TCP/IP stack is implemented in the kernel and your interface is the routing table. Your best bet is to manually assign a route.

You could also use the netlink library to add/remove routes on-the-fly, but some portion of the TCP packets are going to go across the 'wrong' interface until the call is made. You will probably come up against routing issues when your packets with the original interface's address are emitted via another interface.

BigMikeD
+1  A: 

While it's not exactly the pure C option that you're looking for perhaps you could use an iptables rule upon receipt of the accept().

(although a quick look at /lib/iptables shows that you might be in luck)

I'm imagining a rule that would redirect all tcp traffic to your nominated device. You could possibly even make the rule aware of the socket state so that you didn't need to nominate the interface after the accept().


All of this applies until I spot the obvious flaw in the scheme, slap my head and say "D'oh!"

Andrew Edgecombe
A: 

Hello, You can change the route in your program whith the rtnetlink. You can modify all the parameters you want. See also netdevice.

A: 

Thank you all for your answers. I will look up the iptables rule.

I can not change the routes, even Iptables may not be a perfect solution, as the application will be widely deployed, and these tricks may effect other network applications on those machines.

foo