Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 788
Christian Avatar asked Mar 15 '13 10:03

Christian


People also ask

How do you calculate network address from subnet mask and IP address?

To calculate the IP Address Subnet you need to perform a bit-wise AND operation (1+1=1, 1+0 or 0+1 =0, 0+0=0) on the host IP address and subnet mask. The result is the subnet address in which the host is situated.

How do I calculate the number of network addresses?

In simple words, the Number of hosts in any network can be calculated with the formula = 2x– 2, where x is the number of host ID bits in the IP address.

How is IP calculated from Netmask?

IPv4 addresses are 32 bits made up of four octets of 8 bits each. To calculate the subnet mask, convert an IP address to binary, perform the calculation and then convert back to the IPv4 decimal number representation known as a dotted quad. The same subnetting procedure works for IPv6 addresses.


1 Answers

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.%d\n" "$((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.%d\n" "$((i1 & m1))" "$((i2 & m2))" "$((i3 & m3))" "$((i4 & m4))"
10.0.14.96
like image 185
kamituel Avatar answered Oct 02 '22 05:10

kamituel