How to get lan ip address as output in arch linux (Manjaro)

Posted on

Problem :

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 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 I even installed the dnsutils.

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

Solution :

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:, 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 | 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.

Leave a Reply

Your email address will not be published.