Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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

local machine
udp dest:192.168.10.1/255.255.255.0 port 2222

should become (before leaving the local machine):

udp dest:192.168.10.1/255.255.255.0 port 3333

What I tried is this iptables rule:

iptables -t nat -A OUTPUT -d 192.168.10.1/255.255.255.0 -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?

share|improve this question
    
I would suggest just doing it in the process. You can LD_PRELOAD an interceptor library that hooks bind, recvmsg, and getsockname. –  David Schwartz Dec 6 '12 at 18:16
add comment

2 Answers 2

up vote 1 down vote accepted

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.

share|improve this answer
    
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. –  tsv.dimitrov Dec 7 '12 at 7:29
add comment

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).

share|improve this answer
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 '12 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! –  tsv.dimitrov Dec 6 '12 at 16:09
add comment

Your Answer

 
discard

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.