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.
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.
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}'
wlan0
with eth0
in my case but when I start the first line of your answer, I don't have any input. What actually should be do this ? –
Lewison ip route
command. –
Lewison ip
before /xx
to be 0
. Like the example in question 192.168.1.0/24
. –
Lewison 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
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}')
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
.
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
© 2022 - 2024 — McMap. All rights reserved.
8.8.8.8 via 192.168.1.1 dev eth0 src 192.168.1.5
( the IPs are not real - only for example ) – Lewison/24
is not in your output ofip
command but you want to get it in final output? – Lubinip
command . – Lewisonip
and in the end add/24
.ip route' output is:
192.168.1.0/24 ` where the last number before` is
0`. – Lewison192.168.0.0/16
), but even then the subnet does not have to be/16
. It could be/24
, as in your example, or even anything else from16-32
. – Overtlyip route get
does not provide the information needed to print the proper subnet information. – Overtly