1

I am trying to get the network mask using bash in that way:

192.168.1.0/x 

I tried with:

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

but the output is:

192.168.1.123/x

So this way doesn't work for me.

ValeriRangelov
  • 603
  • 2
  • 8
  • 18
  • 1
    Possible duplicate of: [Given the IP and netmask, how can I calculate the network address using bash?](http://stackoverflow.com/questions/15429420/given-the-ip-and-netmask-how-can-i-calculate-the-network-address-using-bash) – Kadir Nov 28 '15 at 08:27
  • Network or mask or both? – Cyrus Nov 28 '15 at 09:41

1 Answers1

5

Since you are masking the last 8 bits, 192.168.1.123/24 is the same as 192.168.1.0/24. If you want the last byte to be 0 for cosmetic reasons, I would use sub() in awk:

ip -o -f inet addr show | awk '/scope global/{sub(/[^.]+\//,"0/",$4);print $4}'
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • I lost all hope in bash and have written c helper – ayvango Dec 21 '17 at 01:03
  • That's a good idea. :) I started to implement it in awk, but bitwise operations can produce surprising results in awk. (Especially since awk has no way to get a 4byte unsigned integer). Following the gawk manual: `In short, using gawk for any but the simplest kind of bitwise operations is probably a bad idea; caveat emptor`.. Btw, I can also recommend Python's `ipaddr` and `netaddr` libraries. They are very convenient to use. – hek2mgl Dec 21 '17 at 01:07