#!/bin/ksh # # This script produces subnet number and broadcast address # according to network number, subnet number and hosts number # per subnet. # set -A network ${1//(\D)/ } if [ $# -ne 3 ]; then echo echo Usage: $0 netwok_number subnet_number hosts_per_subnet echo echo For example: echo echo " $0 192.9.200.0 3 20" echo exit fi # Check the network number format if [ ${#network[*]} -ne 4 ]; then echo Invalid network format exit fi # Check the network class invalidation for (( i=0; i<=3; i++ )); do if [ ${network[$i]} -gt 255 ]; then echo Invalid network class. exit elif [ ${network[$i]} -ge 240 ]; then echo The network you input is a multicast address. exit fi done # Check the network class if [ ${network[0]} -le 127 ]; then bits=24 elif [ ${network[0]} -ge 128 ] && [ ${network[0]} -lt 192 ]; then bits=16 else bits=8 fi # Get the bits needed for subnets and hosts while true do if [ $((2**subnet)) -ge $2 ]; then break else (( subnet++ )) fi done while true do if [ $((2**subnet)) -ge $2 ]; then break else (( subnet++ )) fi done while true do if [ $((2**host - 2)) -ge $3 ]; then break else (( host++ )) fi done if [ $(( subnet + host )) -gt $bits ]; then echo Too many subnets or hosts in your configuration exit fi for (( i=31; i > (31 - host); i -- )); do net[$i]=0 done for (( i=0; i <= (31 - host); i ++ )); do net[$i]=1 done for (( l=0; l <= 7 ; l ++ )); do (( a[0] += (2**(7 - l) * net[l]))) (( a[1] += (2**(7 - l) * net[l + 8]))) (( a[2] += (2**(7 - l) * net[l + 16]))) (( a[3] += (2**(7 - l) * net[l + 24]))) done echo echo Network prefix: $(( 32 - host )) echo Network mask: ${a[0]}.${a[1]}.${a[2]}.${a[3]} echo Total subnets: $(( 2**(bits - host))) echo Hosts per subnet: $(( 2**host - 2)) echo echo list $2 out of $(( 2**(bits - host))) subnets:: echo for i in ${network[*]} do j=7 while [ $j -ge 0 ] do k=$((2**$j)) if [ $(( $i & $k )) -eq $k ]; then net[n]=1 broadcast[n]=1 else net[n]=0 broadcast[n]=0 fi (( n ++ )) (( j -- )) done done for (( i=31; i > (31 - host); i -- )); do net[$i]=0 broadcast[$i]=1 done #for (( i=0; i < (2**subnet); i ++ )); do for (( i=0; i < $2; i ++ )); do set -A a for (( j=0; j < subnet; j ++ )); do k=$((2**$j)) if [ $(( $i & $k )) -eq $k ]; then net[$((32 - host - subnet + j))]=1 broadcast[$((32 - host - subnet + j))]=1 else net[$((32 - host - subnet + j))]=0 broadcast[$((32 - host - subnet + j))]=0 fi done for (( l=0; l <= 7 ; l ++ )); do (( a[0] += (2**(7 - l) * net[l]))) (( a[1] += (2**(7 - l) * net[l + 8]))) (( a[2] += (2**(7 - l) * net[l + 16]))) (( a[3] += (2**(7 - l) * net[l + 24]))) (( a[4] += (2**(7 - l) * broadcast[l]))) (( a[5] += (2**(7 - l) * broadcast[l + 8]))) (( a[6] += (2**(7 - l) * broadcast[l + 16]))) (( a[7] += (2**(7 - l) * broadcast[l + 24]))) done echo Network number: ${a[0]}.${a[1]}.${a[2]}.${a[3]} " " Broadcast address: ${a[4]}.${a[5]}.${a[6]}.${a[7]} done