Given IP address and Netmask, how can I calculate the subnet range using bash?

前端 未结 4 2032
南旧
南旧 2021-01-07 05:12

In a bash script I have an IP address like 140.179.220.200 and a netmask like 255.255.224.0. I now want to calculate the Network address(140.179.192.000), first usable Host

4条回答
  •  独厮守ぢ
    2021-01-07 06:08

    Calculate network and broadcast with bash:

    #!/bin/bash
    
    ip=$1; mask=$2
    
    IFS=. read -r i1 i2 i3 i4 <<< "$ip"
    IFS=. read -r m1 m2 m3 m4 <<< "$mask"
    
    echo "network:   $((i1 & m1)).$((i2 & m2)).$((i3 & m3)).$((i4 & m4))"
    echo "broadcast: $((i1 & m1 | 255-m1)).$((i2 & m2 | 255-m2)).$((i3 & m3 | 255-m3)).$((i4 & m4 | 255-m4))"
    echo "first IP:  $((i1 & m1)).$((i2 & m2)).$((i3 & m3)).$(((i4 & m4)+1))"
    echo "last IP:   $((i1 & m1 | 255-m1)).$((i2 & m2 | 255-m2)).$((i3 & m3 | 255-m3)).$(((i4 & m4 | 255-m4)-1))"
    

    Example: ./script.sh 140.179.220.200 255.255.224.0

    Output:

    network:   140.179.192.0
    broadcast: 140.179.223.255
    first IP:  140.179.192.1
    last IP:   140.179.223.254
    
    • A bitwise AND between IP and mask give the network address.
    • A bitwise OR between the network address and the inverted mask give the broadcast address.

提交回复
热议问题