re: Command for Local IP Address VIEW POST


Never really considered it "hard" - it's like anything: you just need to know what tool to use. I mean, if you were on Windows, you'd need to know, "I want to use ipconfig to query interface information from the CLI". Fun thing is, with UNIX and Linux, there's generally a half dozen ways to skin a cat.

You can do as you posted — using ip addr show, though, I'd probably compress it a bit to:

ip addr show eth0 | awk '/ inet /{print $2}' | cut -f1 -d'/'

That said, depending on what the underlying hardware is, udev rules in place, etc. The above could either return null or error since eth0 may not exist. A more-generalized method would be:

ip addr show dev $(awk '$2 == 00000000 { print $1 }' /proc/net/route) | \
  awk '$1 == "inet" { sub("/.*", "", $2); print $2 }'

Which basically looks at your routing to see what device your default routed corresponds to, then pulls out the IP of the address associated with that programatically-determined interface.

Downside to the (notionally) more-flexible method being being that, if you have multiple IPs aliased onto the same network device, you'll get multiple outputs. It's also even less compact than what you were complaining about.

So, assuming your Linux install has "hostname" installed, using "hostname -i" (vice "hostname -I") will show your default interface's base IP address (using "-I" will show the base IP address plus any aliases).

code of conduct - report abuse