Command for Local IP Address

github logo ・1 min read

I don't know why it's so hard to find the local IP address. It's like the tool designers have gone out of their way to make it as hard as possible. I recently needed to extract the local IP address and it took me a while but I came up with the following

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

If anyone has a better way then let me know because that can't be the simplest way to do it.

twitter logo DISCUSS (5)
markdown guide

this will work if you your device is not eth0

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

prints out all connected devices ip addresses

ifconfig | grep 'inet ' | awk '{print $2}' | cut -f1 -d'/'

The problem here is that general Linux and unix-based systems supports quite well to work with multiple network interfaces at once. There's no "local IP" as every IP can be a local one and the computer have pretty much no way to know.

As an example, when working on my laptop, I'm usually plugged on Ethernet and Wi-fi, which means that I have two local IPs; one for the wlp2s0 (Wi-fi) interface, one for the enp1s0 (ethernet) interface.


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).


Give $ hostname -I a whirl, if you're on linux.

Classic DEV Post from May 18

Aim to Never Stop Learning

It's OK to not know everything. It's OK to be wrong.

david karapetyan profile image
Dispassionate problem solver. I enjoy building minimal and efficient systems. I like to think I don't drink the kool-aid