[bash] Given the IP and netmask, how can I calculate the network address using bash?

Given the IP and netmask, how can I calculate the network address using bash?

 

 

In a bash script I have an IP address like 192.168.1.15 and a netmask like 255.255.0.0. I now want to calculate the start address of this network, that means using the &-operator on both addresses. In the example, the result would be 192.168.0.0. Does someone have something like this ready? I’m looking for an elegant way to deal with ip addresses from bash

 

up vote28down voteaccepted

Use bitwise & (AND) operator:

$ IFS=. read -r i1 i2 i3 i4 <<< "192.168.1.15"
$ IFS=. read -r m1 m2 m3 m4 <<< "255.255.0.0"
$ printf "%d.%d.%d.%dn" "$((i1 & m1))" "$((i2 & m2))" "$((i3 & m3))" "$((i4 & m4))"
192.168.0.0

Example with another IP and mask:

$ IFS=. read -r i1 i2 i3 i4 <<< "10.0.14.97"
$ IFS=. read -r m1 m2 m3 m4 <<< "255.255.255.248"
$ printf "%d.%d.%d.%dn" "$((i1 & m1))" "$((i2 & m2))" "$((i3 & m3))" "$((i4 & m4))"
10.0.14.96

shareimprove this answer

edited Aug 26 ’14 at 6:36

answered Mar 15 ’13 at 10:18

 

https://www.gravatar.com/avatar/21f80e8ae8c0da98241d8a0e07f94e7b?s=32&d=identicon&r=PG

 

kamituel

19.6k24267

 

1

 

Thank you so much! Exactly what I was looking for, beautiful! – Christian Mar 15 ’13 at 16:18

  

 

This is brilliant. Thank you for taking the time to develop it. – jacksonecac Feb 28 at 20:32

add a comment

 

Schreibe einen Kommentar