In a bash script I have an IP address like 140.179.220.200 and a netmask like 255.255.224.0. I now want to calculate the Network address(140.179.192.000), first usable Host IP(140.179.192.1), last usable Host IP(140.179.220.254), and the Broadcast Address(140.179.223.255). I was able to find a clean way to do the network address below. I'm able to do subnet calculations by hand, but mainly having difficulties translating that into a bash script. Thanks in advance
$ 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
Calculate network and broadcast with bash:
#!/bin/bash
ip=$1; mask=$2
IFS=. read -r i1 i2 i3 i4 <<< "$ip"
IFS=. read -r m1 m2 m3 m4 <<< "$mask"
echo "network: $((i1 & m1)).$((i2 & m2)).$((i3 & m3)).$((i4 & m4))"
echo "broadcast: $((i1 & m1 | 255-m1)).$((i2 & m2 | 255-m2)).$((i3 & m3 | 255-m3)).$((i4 & m4 | 255-m4))"
echo "first IP: $((i1 & m1)).$((i2 & m2)).$((i3 & m3)).$(((i4 & m4)+1))"
echo "last IP: $((i1 & m1 | 255-m1)).$((i2 & m2 | 255-m2)).$((i3 & m3 | 255-m3)).$(((i4 & m4 | 255-m4)-1))"
Example: ./script.sh 140.179.220.200 255.255.224.0
Output:
network: 140.179.192.0 broadcast: 140.179.223.255 first IP: 140.179.192.1 last IP: 140.179.223.254
install ipcalc and:
ipcalc 140.179.220.200/255.255.224.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With