Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Is it possible to configure IPTables in a way that all outgoing packets to a certain IP and Port are altered with a different port and do the same for incoming packets?

I have to work with a server routinely and the Hoster decided that SSH access will only be possible on port 222 instead of the default 22.

This always causes a headache when ssh, scp or rsyncing. You always have to remember to add the port parameter.

I would like to circumvent this with IPTables.

Any help greatly appreciated.

share|improve this question
up vote 4 down vote accepted

Yes it should certainly be possible to setup iptable rules to NAT outgoing traffic. You really should only need to create a rule that deals with the output traffic. You shouldn't need a rule to do anything to the returning packets. The state-ful nature of netfilter will deal with this for you.

You would probably need to use a rule like one of these.

# if you want to redirect requests from the local machine
iptables -t nat -A OUTPUT--destination \
         -p tcp  --dport 22 -j DNAT --to-destination

# if you want to redirect requests on a device inline
iptables -t nat -A PREROUTING --destination \
         -p tcp  --dport 22 -j DNAT --to-destination

Another simple solution would be to simply setup an SSH configuration file for the server and specify the port in your config.

# list of all names, you might commonly use for this host.
Host foo foo.example 
    # real hostname
    Port 222
share|improve this answer
Obviously the ssh config entry is the easier and better option. Thanks a lot! – theduke Feb 1 '12 at 14:21

I would recommend reading this link. If you do decide to do this, I would also highly recommend using the following security steps for SSH and a public facing IP.

  1. Don't allow root logons.
  2. Only allow this port to be open from certain IPs.
  3. Have key based authentication.
  4. Use tools such as denyhosts to block any type of brute force attempts.
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.