Last active
November 4, 2024 08:46
-
-
Save jbeda/16191ad2cec4835de40b to your computer and use it in GitHub Desktop.
IP CIDR math in bash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function increment_ipv4 { | |
local ip_base=$1 | |
local incr_amount=$2 | |
local -a ip_components | |
local ip_regex="([0-9]+).([0-9]+).([0-9]+).([0-9]+)" | |
[[ $ip_base =~ $ip_regex ]] | |
ip_components=("${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}" "${BASH_REMATCH[3]}" "${BASH_REMATCH[4]}") | |
ip_dec=0 | |
local comp | |
for comp in "${ip_components[@]}"; do | |
ip_dec=$((ip_dec<<8)) | |
ip_dec=$((ip_dec + $comp)) | |
done | |
ip_dec=$((ip_dec + $incr_amount)) | |
ip_components=() | |
local i | |
for ((i=0; i < 4; i++)); do | |
comp=$((ip_dec & 0xFF)) | |
ip_components+=($comp) | |
ip_dec=$((ip_dec>>8)) | |
done | |
echo "${ip_components[3]}.${ip_components[2]}.${ip_components[1]}.${ip_components[0]}" | |
} | |
node_count=1000 | |
next_node="10.244.0.0" | |
node_subnet_size=24 | |
node_subnet_count=$((2 ** (32-$node_subnet_size))) | |
subnets=() | |
for ((node_num=0; node_num<node_count; node_num++)); do | |
subnets+=("$next_node") | |
next_node=$(increment_ipv4 $next_node $node_subnet_count) | |
done | |
echo ${subnets[@]} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function get_network_cidr() { | |
local ip_base=$1 | |
local -a ip_components | |
local ip_mask_bits | |
local ip_regex="([0-9]+).([0-9]+).([0-9]+).([0-9]+)/([0-9]+)" | |
[[ $ip_base =~ $ip_regex ]] | |
ip_components=("${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}" "${BASH_REMATCH[3]}" "${BASH_REMATCH[4]}") | |
ip_mask_bits="${BASH_REMATCH[5]}" | |
local comp | |
local ip_dec | |
ip_dec=0 | |
for comp in "${ip_components[@]}"; do | |
ip_dec=$((ip_dec<<8)) | |
ip_dec=$((ip_dec + $comp)) | |
done | |
local ip_mask | |
ip_mask=$((2**ip_mask_bits-1)) | |
local net_dec=$(($ip_dec & ~$ip_mask)) | |
declare -a net_components | |
local i | |
for ((i=0; i < 4; i++)); do | |
comp=$(($net_dec & 0xFF)) | |
net_components+=($comp) | |
net_dec=$((net_dec>>8)) | |
done | |
echo "${net_components[3]}.${net_components[2]}.${net_components[1]}.${net_components[0]}/${ip_mask_bits}" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This was very handy, thank you for sharing this!