IP address associated with the default route

Posted on Sun 17 May 2015 in Linux • 1 min read

Need a way to determine the IP address which would be used for outbound communication without actually making any outbound connections? Here’s one method.

Tested on Debian, CoreOS, CentOS, and OSX Yosemite.

ifconfig $(
  { route get 4.2.2.2 || route -n; } 2>/dev/null | \
    awk '/UG/ {print $8}; /interface:/ {print $2}' | head -n 1
) | awk '/inet / {print $2}' | sed -e 's/addr://'