Get Subnet mask in Linux using bash

风格不统一 提交于 2021-02-18 09:28:09

问题


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.


回答1:


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}'



回答2:


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



来源:https://stackoverflow.com/questions/33150176/get-subnet-mask-in-linux-using-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!