Paste Search Dynamic
Recent pastes
Calculates network and broadca
  1. #!/bin/bash
  2.  
  3. # Calculates network and broadcast based on supplied ip address and netmask
  4.  
  5. # Usage: broadcast_calc.sh 192.168.0.1 255.255.255.0
  6. # Usage: broadcast_calc.sh 192.168.0.1/24
  7.  
  8.  
  9. tonum() {
  10.     if [[ $1 =~ ([[:digit:]]+)\.([[:digit:]]+)\.([[:digit:]]+)\.([[:digit:]]+) ]]; then
  11.         addr=$(( (${BASH_REMATCH[1]} << 24) + (${BASH_REMATCH[2]} << 16) + (${BASH_REMATCH[3]} << 8) + ${BASH_REMATCH[4]} ))
  12.         eval "$2=\$addr"
  13.     fi
  14. }
  15. toaddr() {
  16.     b1=$(( ($1 & 0xFF000000) >> 24))
  17.     b2=$(( ($1 & 0xFF0000) >> 16))
  18.     b3=$(( ($1 & 0xFF00) >> 8))
  19.     b4=$(( $1 & 0xFF ))
  20.     eval "$2=\$b1.\$b2.\$b3.\$b4"
  21. }
  22.  
  23. if [[ $1 =~ ^([0-9\.]+)/([0-9]+)$ ]]; then
  24.     # CIDR notation
  25.     IPADDR=${BASH_REMATCH[1]}
  26.     NETMASKLEN=${BASH_REMATCH[2]}
  27.     zeros=$((32-NETMASKLEN))
  28.     NETMASKNUM=0
  29.     for (( i=0; i<$zeros; i++ )); do
  30.         NETMASKNUM=$(( (NETMASKNUM << 1) ^ 1 ))
  31.     done
  32.     NETMASKNUM=$((NETMASKNUM ^ 0xFFFFFFFF))
  33.     toaddr $NETMASKNUM NETMASK
  34. else
  35.     IPADDR=${1:-192.168.1.1}
  36.     NETMASK=${2:-255.255.255.0}
  37. fi
  38.  
  39. tonum $IPADDR IPADDRNUM
  40. tonum $NETMASK NETMASKNUM
  41.  
  42. #printf "IPADDRNUM: %x\n" $IPADDRNUM
  43. #printf "NETMASKNUM: %x\n" $NETMASKNUM
  44.  
  45. # The logic to calculate network and broadcast
  46. INVNETMASKNUM=$(( 0xFFFFFFFF ^ NETMASKNUM ))
  47. NETWORKNUM=$(( IPADDRNUM & NETMASKNUM ))
  48. BROADCASTNUM=$(( INVNETMASKNUM | NETWORKNUM ))
  49.  
  50. IPADDRBIN=$(   python -c "print(bin(${IPADDRNUM}   )[2:].zfill(32))")
  51. NETMASKBIN=$(  python -c "print(bin(${NETMASKNUM}  )[2:].zfill(32))")
  52. NETWORKBIN=$(  python -c "print(bin(${NETWORKNUM}  )[2:].zfill(32))")
  53. BROADCASTBIN=$(python -c "print(bin(${BROADCASTNUM})[2:].zfill(32))")
  54.  
  55. toaddr $NETWORKNUM NETWORK
  56. toaddr $BROADCASTNUM BROADCAST
  57.  
  58. printf "%-25s %s\n" "IPADDR=$IPADDR"       $IPADDRBIN
  59. printf "%-25s %s\n" "NETMASK=$NETMASK"     $NETMASKBIN
  60. printf "%-25s %s\n" "NETWORK=$NETWORK"     $NETWORKBIN
  61. printf "%-25s %s\n" "BROADCAST=$BROADCAST" $BROADCASTBIN
Parsed in 0.014 seconds