#!/bin/bash # Finding common network for 2 ipv4 arguments # # (C) 2016-2020 Felix Hauri - felix@f-hauri.ch # Licensed under terms of LGPL v3. www.gnu.org # # Usage: $0 xxx.xxx.xxx.xxx yyy.yyy.yyy.yyy (two IPv4 Address) ip2int() { local _a=(${1//./ }) printf ${2+-v} $2 "%u" $((_a<<24 |${_a[1]}<< 16|${_a[2]}<< 8|${_a[3]})) } int2ip() { printf ${2+-v} $2 "%d.%d.%d.%d" \ $(($1>>24)) $(($1>>16&255)) $(($1>>8&255)) $(($1&255)) } mask2int() { printf ${2+-v} $2 "%u" $(( ( ~0 ^ ~0<<32 ) ^ ( ~0 ^ ~0<<(32-$1) ) )) } shopt -s extglob int2bin () { local _fmt="" _i _p printf -v _fmt "_out=\${_out//%s/%%03o};" {0..7} printf -v _fmt "$_fmt\n" 0 1 8 9 64 65 72 73 eval "${FUNCNAME}()"'{ local _out;printf -v _out "%o" $1;'${_fmt}' printf -v _out "%32s" ${_out##*(0)}; _out=${_out// /0}; printf -v _out "%s %s %s %s" \ ${_out:0:8} ${_out:8:8} ${_out:16:8} ${_out:24:8}; _p=$(($2+($2>8)+($2>16)+($2>24))) && printf -v _out "%s.%s" "${_out:0:_p}" "${_out:_p}"; printf -v $3 "%s" "$_out";}' $FUNCNAME $@ } ip2int $1 ip1 ip2int $2 ip2 for((i=0;i<32;i++)){ (( ((ip1>>(31-i))&1) == ((ip2>>(31-i))&1) )) || break } lmask=$i mask2int $lmask mask ((ip1>ip2))&&{ ipC=$ip1;ip1=$ip2;ip2=$ipC; } inetbase=$((ip1&mask)) ibrdcast=$(((mask ^ ( ~0 ^ ~0<<32 )) | ip1 )) cnt=$((ibrdcast-inetbase-1)) int2ip $inetbase netbase int2ip $mask netmask int2ip $((inetbase|1)) first int2ip $((ibrdcast-1)) last int2ip $ibrdcast broadcast int2ip $ip1 sub1 int2ip $ip2 sub2 int2bin $inetbase $lmask bnetbase int2bin $mask $lmask bnetmask int2bin $((inetbase|1)) $lmask bfirst int2bin $((ibrdcast-1)) $lmask blast int2bin $ibrdcast $lmask bbroadcast int2bin $ip1 $lmask bsub1 int2bin $ip2 $lmask bsub2 printf " %-23s: %-32s %s\n" \ Network "$netbase/$lmask ($cnt hosts)" "$bnetbase" \ Netmask $netmask "$bnetmask" \ Broadcast $broadcast "$bbroadcast" \ First\ host $first "$bfirst" \ "ArgMin (hst $((ip1-inetbase)))" $sub1 "$bsub1" \ "ArgMax (hst $((ip2-inetbase)))" $sub2 "$bsub2" \ Last\ host $last "$blast"