Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 287
ValeriRangelov Avatar asked Oct 15 '15 13:10

ValeriRangelov


People also ask

How do I find my subnet mask in Linux?

In order to find the subnet mask for your host, use the “ifconfig” command with the interface name and pipe it with the “grep” command to isolate the “mask” string. In this case, you are presented with subnet masks for every network interface (loopback interface included).

How do I find my network ID Linux?

The command for finding your IP Address is ifconfig. When you issue this command you will receive information for every network connection you have available. Most likely you will see information for both the loopback (lo) and your wired network connection (eth0).

How do I find the IP address of a bash script?

Instead, you could just use this: hostname --all-ip-addresses or hostname -I , which does the same thing (gives you ALL IP addresses of the host).


2 Answers

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}'
like image 169
vishal Avatar answered Oct 12 '22 04:10

vishal


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

like image 38
RoyalBigMack Avatar answered Oct 12 '22 05:10

RoyalBigMack