Acquire Subnet Mask on Linux with Bash


Solution 1:

There are a few methods to accomplish this.

The following code can be used to format the mask as when printing.

/sbin/ifconfig wlan0 | awk '/Mask:/{ print $4;} '

To obtain the subnet mask in the format of, the ip command can be utilized.

ip -o -f inet addr show | awk '/scope global/ {print $4}'

Solution 2:

A better approach will be:

 ifconfig eth0 | awk '/netmask/{split($4,a,":"); print a[1]}'

You have the flexibility to replace eth0 with a different interface of your choice.

Solution 3:

One easy method that worked for me was:

IP=$(ifconfig eth0 | grep -w inet | cut -d" " -f10) # device IP, e.g.
IP_RANGE=$(echo $IP | cut -d"." -f1-3).0/24 # subnet

Substitute the incorrect interface, denoted by


, with the appropriate one as indicated by



Frequently Asked Questions