Find IPv4 broadcast address of a device

Nils Toedtmann asked:

I need to determine the IPv4 broadcast address of a device (if any) with a shell script. If there are several, pick one (e.g. first as ordered by /sbin/ip).

I have a solution, but i do not like it because it makes assumptions about the output format of /sbin/ip, and i don’t know how stable that output format is across systems.

DEV=eth0
BROADCAST=`ip address show $DEV | grep 'inet .* brd ' | head -1 | sed -e 's/^.* brd ([0-9.]*) .*$/1/'`
echo $BROADCAST

Isn’t there something in /proc/ or /sys/ that i can simply cat? Why not?

I need the solution to work reliably, at least across the Debian/Ubuntu Linux family.


Edit: This is NOT a question about sed/awk/grep magic. The question is:

  • Can i expect ip (of ifconfig for that matter) across architectures and Linux flavours to have the same output format, such that i can reliably parse e.g. an interface’s IPv4 broadcast address from it?
  • If not: is there another way to output an interface’s IPv4 broadcast address in an more predictable manner?
  • Why is there no /proc/sys/net/ipv4/conf/eth0/{address,mask,broadcast} that i can simply cat?

My answer:


awk is your friend.

ip a s dev $DEV | awk '/inet / {print $4}'

View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.