I need to write a script that gets the IP address of the interface that is used for unknown routes (e.g. where is routed through)

That script should work on Ubuntu, Debian, Arch and Mac OS Systems without the need of installing extra packages.

On Ubuntu, I use hostname -I, that gives the primary IP address. But in older versions of ubuntu, debian and arch and in Mac OS the -I-Flag is not available.

Second Idea was to parse the ifconfig-output, but as the naming is very different on each system and in german systems for example there is no addr: but something different, this also won't work.

I need this to write a little script to start up a web-application and a little Python-Webserver to server the static content. The script is then used by our designers that barely can code some html and css but don't know anything about bash.

  • By the way - none of this works in my default ubuntu 15.04 config: stackoverflow.com/questions/13322485/… – Tobi Oct 7 '15 at 13:05
  • 2
    You need to check the default route; in linux e.g. ip ro get and check what IP address is shown after src. I'm sure MacOS has something similar but I think it's wrong to expect one command to work across operating systems. Wrap your check with an OS check. EDIT: this whould work just fine on ubuntu 15.04, you may have to add /sbin and /usr/sbin to your PATH first. Otherwise add to the question why it doesn't work (i.e. edit it, don't add comments for such additional info) – wurtel Oct 7 '15 at 13:06

The command route gives you information about the routes used to access different ip address and also de device name.

$ route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface     *        U     0      0        0 eth0        *          U     0      0        0 eth0
link-local      *          U     1002   0        0 eth0
default         UG    0      0        0 eth0

I think the command is available in all systems you mention.

| improve this answer | |

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.