Acquire Subnet Mask on Linux with Bash

Feedback


Solution 1:

There are a few methods to accomplish this.

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

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

To obtain the subnet mask in the format of 192.168.1.1/24, 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. 11.1.1.43
IP_RANGE=$(echo $IP | cut -d"." -f1-3).0/24 # subnet 11.1.1.0/24

Substitute the incorrect interface, denoted by

eth0

, with the appropriate one as indicated by

ifconfig

.

Frequently Asked Questions