Skip to content

Instantly share code, notes, and snippets.

@vancluever
Created January 27, 2017 21:10
Show Gist options
  • Select an option

  • Save vancluever/a60f80b6cfd5aa8e8c3c6af911442fbd to your computer and use it in GitHub Desktop.

Select an option

Save vancluever/a60f80b6cfd5aa8e8c3c6af911442fbd to your computer and use it in GitHub Desktop.
Bash script to calculate a set of subnets off a network address
#!/usr/bin/env bash
# ip_to_decmial takes a dotted-quad IPv4 address and returns the decimal form
# on stdout.
ip_to_decmial() {
local ip_bytes=(${1//./ })
local ip_decimal=0
for n in 0 1 2 3; do
ip_decimal=$(( ip_decimal | ip_bytes[n] << 8 * 3 - 8 * n ))
done
echo $ip_decimal
}
# decimal_to_ip takes a decimal IPv4 address and returns the dotted-quad form
# on stdout.
decimal_to_ip() {
local ip_decimal=$1
local ip_bytes=()
for n in 0 1 2 3; do
ip_bytes+=($(( (ip_decimal >> 8 * 3 - 8 * n) & 255 )))
done
echo "${ip_bytes[0]}.${ip_bytes[1]}.${ip_bytes[2]}.${ip_bytes[3]}"
}
dec=$(ip_to_decmial "$1")
shift
while (( "$#" )); do
params=(${1/\*/ })
shift
n=1
while [ "${n}" -le "${params[0]}" ]; do
echo "$(decimal_to_ip "${dec}")/${params[1]}"
dec=$((dec + 2 ** (32-params[1])))
((n++))
done
done
@vancluever
Copy link
Copy Markdown
Author

Run this script like so:

./ipcalcandplan.sh 10.0.0.0 4*24 8*25

This would calculate the first 4 /24s, and then the next 8 /25s, starting from 10.0.0.0.

Output:

10.0.0.0/24
10.0.1.0/24
10.0.2.0/24
10.0.3.0/24
10.0.4.0/25
10.0.4.128/25
10.0.5.0/25
10.0.5.128/25
10.0.6.0/25
10.0.6.128/25
10.0.7.0/25
10.0.7.128/25

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment