Suppose you have one or more network interfaces, and they have one or more assigned IP addresses, also called aliases. If you need to find out which IP address and interface will be used as a default “source” by your Linux box, you need to execute the following:
ip route get 8.8.8.8
This, of course, assumes that 8.8.8.8 is not directly connected on your networks somehow. Since this is one of the Public Name Servers of Google, I think it is safe to assume so.
A sample output of the ip command follows:
8.8.8.8 via 10.0.2.2 dev eth0 src 10.0.2.15 cache
The output is pretty much self-explanatory — the route to “8.8.8.8” will originate from device “eth0”, the used source IP address will be “10.0.2.15”, and the next hop, the (default) gateway, will be “10.0.2.2”.
This method is 100% reliable. The man page of “ip” says that “this command gets a single route to a destination and prints its contents exactly as the kernel sees it”.
References:
May 29, 2012 at 10:44 pm
Hello!
Thanks for the tip. ๐
Nevertheless it does not work within an OpenVZ container.
Is there a reliable way to get the second hop? (“traceroute -n -m 2 8.8.8.8” seems useless)
Thanks.
May 30, 2012 at 10:13 am
Hi. I’ve tested it in one of my OpenVZ containers and it works properly:
The default source IP is properly detected as “30.40.50.60” which belongs to “venet0:0”.
Note that I run the default OpenVZ guest configuration where containers have public IP addresses. If you are running your VZ guests behind a NAT, that’s a different story. The article here demonstrates how to get the default outgoing IP address of the machine (which may be a private one), not its real IP address if it’s behind a NAT.
—
Regarding the “traceroute” parsing — I don’t recommend it, since “traceroute” is making real network tests which could take a while. Here is an example on how to parse it though:
The “egrep” is there just as a sanity check that the “head|tail” commands really returned the second hop.
May 30, 2012 at 6:21 pm
Hello!
> “not its real IP address if itโs behind a NAT”
That is the case: all VMs use venet and are “hidden” in a private network.
And sadly, traceroute always returns the node primary IP adress, not the IP failover used by some containers.
Anyway, thank you for your help! ๐
May 31, 2012 at 8:11 am
๐ You are welcome. It’s even theoretically impossible to find out the real IP address from the NAT’ed machine, since IP headers rewriting is done outside of the machine, at the router.
The only solution if you want to figure this out from the local machine, is to query a remote server connected in Internet and ask it to echo your remote IP address. For example, I put the following PHP script at “http://www.famzah.net/temp/ip.php”:
Then queried for my real IP address in the following way:
September 24, 2015 at 11:09 pm
ip route get 8.8.8.8 | awk ‘ NR == 1 {print $NF}’