Is it possible to redirect all calls to an external IP on internet, to localhost (without use of hosts)?

I have an old application and I don't have the source code and this application try to connect to a postgres server using an IP

Can I instruct ubuntu to redirect all callings to this external IP to localhost?

In this way, I'll be able to run a postgres server on localhost and work with my application.

note: the application uses the IP, not the dns.


1 Answer 1


Iptables is the way to go.

sysctl -w net.ipv4.conf.eth0.route_localnet=1 # to enable redirecting to localhost
EXTERNAL_IP= #change this line to reflect external ipaddress
sudo iptables -t nat -A OUTPUT -d ${EXTERNAL_IP} -j DNAT --to-destination

Breaking it down

  • -t nat allows you to refer to as a valid destination.

  • -A OUTPUT, appends to the OUTPUT chain of iptables. This is a built-in chain. Other built-in chains exist like INPUT, which applies to incoming packets and PREPROCESSING, which applies to all incoming packets before any other bulit-in chain gets to them. You can also make your own chains and append them to one of these built-in chains for better management of your settings.

  • -d ${EXTERNAL_IP} filters on the destination IP-address of packets going through OUTPUT chain.

  • -j DNAT sets the target of the rule to DNAT, which allows you to modify destination address of packets.

  • --to-destination is parameter to the DNAT target that specifies what to change about these matching packets.

You can also limit redirected ports of an address by using --dports ${ORIGINAL_PORT_NUMBER} after -d ${EXTERNAL_IP} and have them re-route to specific port by appending port to like so${FINAL_PORT_NUMBER}.


use the following to remove from iptables.

# note: -A is replaced by -D
sudo iptables -t nat -D OUTPUT -d ${EXTERNAL_IP} -j DNAT --to-destination

and check iptables listings with sudo iptables -t nat -L -n -v where -t nat allows you to look at iptables mappings including ones that pertain to NAT.

Further actions

You may also need to masquerade or redirect packets from your postgres server to match external IP addresses and expected port if you plan to communicate with the application and the application checks source IP address and port.


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.