I need to change the outgoing port number of all UDP packets originating from a local process. For example:

local machine
udp dest: port 2222

should become (before leaving the local machine):

udp dest: port 3333

What I tried is this iptables rule:

iptables -t nat -A OUTPUT -d -p udp --dport 2222 -j DNAT  --to-destination :3333

However it changes also the destination IP address. From another question in serverfault I saw that according to netfilter documentation ( http://www.netfilter.org/documentation/HOWTO/NAT-HOWTO.txt, section 6.3.7) iptables can't do this.

My question is how can I accomplish this task in Linux? Maybe there is another tool which can do the job?

  • I would suggest just doing it in the process. You can LD_PRELOAD an interceptor library that hooks bind, recvmsg, and getsockname. Dec 6, 2012 at 18:16

2 Answers 2


I can't think of any tool that would do that out of the box. This is quite rare scenario, as you can't create correct two-way NAT mapping if you only change port. Do you really need just one-way traffic ?

However you can always write your own netfilter module (it's not that difficult) and alter packet headers in any way you want.

  • The main point was to change the destination port only. If I don't touch the source port, the connection will work fine. You are right that there is no such tool, so after measuring the alternatives I agree that custom netfilter module is the way to go. Dec 7, 2012 at 7:29

You might be able to accomplish this with Divert Sockets, though I've never used it for this particular purpose, and haven't tried it on a modern kernel.

Here's the project page for the linux port. Basically, this adds a job to iptables that allows you to redirect packets into user space and modify before sending them back out on the wire (or dropping them completely).

  • 1
    That might work, but as I understand it requires programming skills too, and I'd recommends writing netfilter module instead, as packet processing will be much faster then.
    – Eugene
    Dec 6, 2012 at 15:32
  • Yes, I agree with Eugene. I considered both diverted sockets and netfilter module. However non-programming solution is preferred. My colleagues suggest a workaround to redirect to localhost and then masquerade. I'll keep you posted on the final solution. Thanks for the comments! Dec 6, 2012 at 16:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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