6

I have a script which I used to use in ubuntu. It got my lan ip address using the command hostname -I. I would get an output like 192.168.1.xxx as a string which I can use somewhere else.

However, with Manjaro, the command doesn't exist, when I tried hostname -i, (lowercase) but i get 127.0.1.1. I even installed the dnsutils.

Is there a way I can get my lan address as an output from any command / tool in Manjaro?

anarchy
  • 207
  • 1
  • 2
  • 7
  • By "lan IP address".. do you mean the gateway or YOU? Are you familiar with `ifconfig` or `ip addr` .. to narrow down *stuff*.. look at the command lines (man) for these commands. – Señor CMasMas May 17 '21 at 19:09
  • i meant ME not the gateway – anarchy May 17 '21 at 19:11
  • those commands give me a whole lot of junk, i just need 1 line which is my own ip address on the LAN. so 192.168.1.90, the gateway is 192.168.1.254 – anarchy May 17 '21 at 19:12
  • Use `ip addr` or `ifconfig`. The options go on and on (unfortunate for us) ... but for instance.. `ip a show eth0` .. `ifconfig | grep -A 1 'eth0' | tail -1 | cut -d ':' -f 2 | cut -d ' ' -f 1` or `ip -o -4 addr list eth0 | awk '{print $4}' | cut -d/ -f1` . – Señor CMasMas May 17 '21 at 19:15
  • "those commands give me a whole lot of junk" .. you are using the wrong operating system. – Señor CMasMas May 17 '21 at 19:16
  • lol i mean i use these commands in other system to get information i need, its just that i had easier access to this function there. i guess things need to be done a bit manually here – anarchy May 17 '21 at 19:16
  • 2
    Home in on `ip -o -4 addr list eth0 | awk '{print $4}' | cut -d/ -f1` – Señor CMasMas May 17 '21 at 19:17
  • Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/124358/discussion-between-anarchy-and-senor-cmasmas). – anarchy May 17 '21 at 19:27

1 Answers1

9

Linux iproute2 tools have been supporting JSON output since 2017. This output is then easily parsable with the jq utility (which is distributed in most distributions, including Manjaro) for use in scripts.

You can combine this with asking the kernel how it would choose to reach some well known address (eg: 8.8.8.8), and keep only the relevant part (among other information such as the gateway, the interface name etc.): the chosen local address ("prefsrc") using a jq filter. No packet is emitted, it's just asking the kernel to resolve a route and give back the result:

ip -json route get 8.8.8.8 | jq -r '.[].prefsrc'

will give the result which won't be affected by any output peculiarities nor requires to know beforehand the interface name. This result is dynamic. For example if one then uses a VPN for all traffic, the previous command would return the new tunnel address instead.

A.B
  • 5,338
  • 1
  • 17
  • 20