0

I'm having trouble making sense of all the iptable examples out there.

I simple want all requests from my machine to host A on port 3306 to actually go to host B on port 3306. How can I do this?

Matthew Herbst
  • 157
  • 1
  • 7

1 Answers1

1

Assuming you only want to redirect the connections originating from your machine (as opposed to forwarded by your machine), the following rules should suffice:

iptables -t nat -A OUTPUT -d hostA -p tcp --dport 3306 -j DNAT --to hostB
iptables -t nat -A INPUT  -s hostB -p tcp --sport 3306 -j SNAT --to hostA

The first one consists in changing the destination address of the outgoing packets from hostA to hostB.

When hostB sends packets back, the second rule rewrites the source address from hostB to hostA so as not to confuse the client.

To마SE
  • 168
  • 1
  • 1
  • 5
  • Perfect, thank you! As a side question, is it possible to use hostnames instead of IPs? – Matthew Herbst May 16 '16 at 19:23
  • @MatthewHerbst It is possible to use hostnames instead, but there are pitfalls. From what I know, iptables resolves the hostname and stores an IP address in memory only once, when it loads the rule. And it will most likely fail if for some reason you cannot reach a DNS server (unless the hostname is hardcoded in /etc/hosts, for instance). I've always steered clear from using hostnames in iptables. If you want to do something involving hostnames, you'll probably have to do something more complicated like marking the packets with a user-level application such as squid. – To마SE May 16 '16 at 19:39
  • Makes sense. I'll probably just stick with the IPs for now. Thanks again – Matthew Herbst May 16 '16 at 19:43