On 16 Mar 14:44, Mark Rogers wrote:
What's the best way (programatically) to determine the local IP which would be used to make a connection to a specific destination?
By way of example, the following works:
$ tracepath -n 192.168.251.132 1: 192.168.251.140 3.816ms pmtu 1500 1: ...
$ tracepath -n 10.0.0.1 1: 10.0.0.140 1.455ms pmtu 1500 1: ...
In other words the PC I ran it on has several IP addresses (and several interfaces), but from the above I can determine that for destination 192.168.251.132 by source IP will be 192.168.251.140, but for destination 10.0.0.1 it will be 10.0.0.140.
However this is quite slow and messy, and there is surely a better way!
ip route get <destinationip> | sed -e '1 { s#.*src ##; p; }; d'
That gives:
$ ip route get 8.8.8.8 | sed -e '1 { s#.*src ##; p; }; d' 10.124.150.80 $ ip route get 192.168.1.250 | sed -e '1 { s#.*src ##; p; }; d' 192.168.1.1 $
The ip program is part of the iproute2 package, and is "really useful" (tm).