Linux – Find IPv4 broadcast address of a device

bashdebianlinux

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?

Best Answer

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

I wouldn't. Though ifconfig is dead and so shouldn't change to much, there have been minor changes applied by distros to keep this deprecated tool somewhat functional since many people don't seem to want to learn how to make the switch. The output of ip really isnt' great for parsing IMO.

If not: is there another way to output an interface's IPv4 broadcast address in an more predictable manner?

If I were you I would probably look at installing and using a tool like facter to do the work for you. I don't think it gives you the broadcast address directly, but it should be trivial to take the address/netmask and perform the math to get the broadcast address.

Why is there no /proc/sys/net/...

iproute2 connects to the the kernel via the NETLINK socket. Ifconfig uses the ioctl method which is deprecated. If you want to get the correct information without scraping the output of some user-space program or installing something, then you'll need to use one of those API.

If you want you can do something like strace ip addr show or strace ifconfig to see the output of exactly what those tools are doing to retrieve the values.

I don't know the history of why, but that isn't a question for this site. This is the way it is. If you want 'why' go talk to the kernel devs.