Make an outgoing network connection via a specific outgoing IP address on linux
I have a Ubuntu (18.04) linux server with a main network interface eth0
, which has 2 IP addresses assigned to it (via systemd-networkd
). The ip route
routing details are pretty simple, just send all outgoing stuff over IP1. However sometimes I need to make outgoing connections (i.e. ssh connections) that come out from the other IP address, IP2. I could just change the default route for this entire server, but is there a better way? Can I run magiccommand --use-ip=$IP2 ssh whatever
I have root on the machine. I tried firejail, but it errored with Error: the software is not supported for /31 networks
?!) I want to ssh into another server which only allows SSH connections from IP2, not IP1.
Recent enough versions of ssh
have the -B bind_interface
and -b bind_address
options.
Ubuntu 18.04's ssh might only have the -b bind_address
option which is the one needed here anyway. So to use IP2 as source IP address when connecting instead of the default IP address hinted by the routes, one can do:
ssh -b $IP2 whatever
If you have multiple interfaces, you can bind to a specific interface or IP address. This needs to be supported by the application. Applications that support it often have commandline parameters for that. There is no standard as to which commandline parameters are used.
For ssh
, man ssh
says:
-B bind_interface
Bind to the address of bind_interface before attempting to connect to the destination host. This is only useful on systems with more than one
address.
-b bind_address
Use bind_address on the local machine as the source address of the connection. Only useful on systems with more than one address.
So you can either use the interface or IP address.