Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given IP address and Netmask, how can I calculate the subnet range using bash?

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
like image 633
namesjj Avatar asked Sep 20 '25 12:09

namesjj


2 Answers

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
  • A bitwise AND between IP and mask give the network address.
  • A bitwise OR between the network address and the inverted mask give the broadcast address.
like image 61
Cyrus Avatar answered Sep 22 '25 08:09

Cyrus


install ipcalc and:

ipcalc 140.179.220.200/255.255.224.0
like image 31
tso Avatar answered Sep 22 '25 08:09

tso