Given the IP and netmask, how can I calculate the network address using bash?

后端 未结 6 924
耶瑟儿~
耶瑟儿~ 2020-12-24 03:20

In a bash script I have an IP address like 192.168.1.15 and a netmask like 255.255.0.0. I now want to calculate the start address of this network, that means using the &

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-24 03:47

    Some Bash functions summarizing all other answers.

    ip2int()
    {
        local a b c d
        { IFS=. read a b c d; } <<< $1
        echo $(((((((a << 8) | b) << 8) | c) << 8) | d))
    }
    
    int2ip()
    {
        local ui32=$1; shift
        local ip n
        for n in 1 2 3 4; do
            ip=$((ui32 & 0xff))${ip:+.}$ip
            ui32=$((ui32 >> 8))
        done
        echo $ip
    }
    
    netmask()
    # Example: netmask 24 => 255.255.255.0
    {
        local mask=$((0xffffffff << (32 - $1))); shift
        int2ip $mask
    }
    
    
    broadcast()
    # Example: broadcast 192.0.2.0 24 => 192.0.2.255
    {
        local addr=$(ip2int $1); shift
        local mask=$((0xffffffff << (32 -$1))); shift
        int2ip $((addr | ~mask))
    }
    
    network()
    # Example: network 192.0.2.0 24 => 192.0.2.0
    {
        local addr=$(ip2int $1); shift
        local mask=$((0xffffffff << (32 -$1))); shift
        int2ip $((addr & mask))
    }
    

提交回复
热议问题