ValeriRangelov
ValeriRangelov

Reputation: 633

Get Subnet mask in Linux using bash

I am using bash to get the IP address of my machine with that script:

_MyGW="$( ip route get 8.8.8.8 | awk 'N=3 {print $N}' )"

And now I am trying to get the Subnet Mask in this type:

192.168.1.0/24 

But I have no idea how can I do that.

Upvotes: 30

Views: 97829

Answers (5)

se_pavel
se_pavel

Reputation: 2208

INTERFACE=$(ip -o -f inet route |grep -e "^default" |awk '{print $5}')

echo $(ip -o -f inet addr show | grep "$INTERFACE" | awk '/scope global/ {print $4}')

Upvotes: 2

some guy
some guy

Reputation: 306

That's how I get the IP and subnet mask with bash/awk:

IFCONFIG=$(ifconfig eth0)
IPETH=$(echo "$IFCONFIG" | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}')
MASK=$(echo "$IFCONFIG" | awk '/Mask/{split($4,a,":"); split(a[2],m,"."); h=m[1]*16777216+m[2]*65536+m[3]*256+m[4]; s=0; for(i=0; i < 32; i++) { s+=and(h,1); h/=2 } print s; }')
echo ${IPETH}/${MASK}

Depending on your version of ifconfig you must use /Mask/ or /netmask/ to get the subnet mask. I need this bit fiddling because I don't have ip on my system.

This gives for me e.g.

172.29.11.12/24

Upvotes: 1

LoW
LoW

Reputation: 604

A simple way of doing it 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

Replace of course eth0 with the right interface diplayed by ifconfig.

Upvotes: 1

RoyalBigMack
RoyalBigMack

Reputation: 716

A better approach will be:

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

You can substitute the eth0 with any other interface you want

Upvotes: 3

vishal
vishal

Reputation: 2391

there are couple of ways to achieve this:

first: to print the mask in format 255.255.255.0, you can use this:

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

second: we can use ip command to get the mask in format 192.168.1.1/24

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

Upvotes: 53

Related Questions