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

I have an application that tries to connect to 10.0.0.172. I would like these connections to be redirected to localhost. What is the best way to achieve this?

(I've just learned that /etc/hosts only works for DNS requests, and not for IP addresses.)

I think I need to write some iptables commands but I've never used those before.

share|improve this question

1 Answer 1

You need to add a rule like this:

iptables -t nat -A PREROUTING -p tcp --dport 80 -s source_ip -j REDIRECT --to-ports 80

The above example redirect all http requests to localhost on same port 80. Of course, you can change the ports and protocol according to your needs. However, there is one more requirement that this host should be receiving this traffic to be able to redirect it (such as your gateway).

If you don't need to filter any traffic, you can just set default policy to ACCEPT for INPUT.

share|improve this answer
    
I'm not only interested in port 80, I want all traffic to 10.0.0.172 be redirected to localhost. –  aioobe Apr 30 '12 at 12:11
    
@aioobe: So, you can remove the part -p tcp --dport 80 and also --to-ports 80 from the above rule. –  Khaled Apr 30 '12 at 12:35
    
...also, I don't know what I should write for source_ip. The local IP which I want to redirect connections to or 10.0.0.172? –  aioobe Apr 30 '12 at 12:43
    
If you don't know the source IP, you can use the option -d destination_ip to apply the rule only to specific destination addresses. –  Khaled Apr 30 '12 at 12:51
    
It could that masquerade is also needed iptables -t nat -A POSTROUTING -p all -j MASQUERADE –  pl1nk Sep 11 '12 at 14:07

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.