3

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.

3

Iptables is the way to go.

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

Breaking it down

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

-A OUTPUT, appends to the OUTPUT chain of iptables. This is built-in chain applies. 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 127.0.0.1 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 127.0.0.1 like so 127.0.0.1:${FINAL_PORT_NUMBER}.

Removal

use the following to remove from iptables.

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

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

Further actions

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

Related

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.