Inside Out

Notes on seeking wisdom and crafting software

Internal Port Redirection

This article will describe how to send packets destined to port x through a port y. Let me start off with the situation that led to port redirection stuff (and hence this article)

The Problem

I have an application X which connects to a remote website on port 5000 and then allows me to do some data transfer. However my system is behind a firewall that blocks all outgoing connection on port 5000. Fortunately the website accepts incoming connection on port 23 (which is surprisingly not blocked by my university firewall). Thats cool, I can connect to on port 23 and do whatever. But the application X doesn’t allow me to change the port settings, i.e, X only connects to sad. And X is “closed source” :-(

The Idea

Well if by some mechanism I can redirect all my outgoing connections to on port 5000 to on port 23 before the packets leave my system, then my problem should be solved. In other words, I’ll change the destination address of all packets to from to !!

I think using a proxy(e.g : tinyproxy) in my localhost will do that. But running a new proxy process for just this small application X din’t seem to be a good idea.

Aha ! here comes the solution (yet another *nix oneliner ;))

Note : In case anything goes wrong just delete the rule and do an iptables-save

iptables -t nat -A OUTPUT -p tcp -d a.b.c.d --dport 5000 -j DNAT --to a.b.c.d:23



-A : Adds a chain-rule to the nat table

OUTPUT : For altering locally-generated packets before routing

-p : Specifies the protocol

-d : Give the destination ipaddress

—dport : Destination port
-j : Jump if the rule matches

DNAT : It specifies that the destination address of the packet should be modified

—to : The destination ipaddress:port

A few more oneliners (just for reference, in case i might forget them..)
  • To DELETE the above rule

`iptables -t nat -D OUTPUT -p tcp -d a.b.c.d --dport 5000 -j DNAT --to a.b.c.d:23` - To check how many packets are redirected

`iptables -L -t nat -nv`

Note: In this article, = :-)

Tags: iptables, linux, network, packet, redirect,, portredirect, dnat, nat, tcp