Bash script to list all IPs in prefix

后端 未结 11 1632
[愿得一人]
[愿得一人] 2020-12-23 12:23

I\'m trying to create script that I can input a set of prefixes, which will then list all IP addresses within the prefixes (including network/host/broadcast).

An ex

11条回答
  •  猫巷女王i
    2020-12-23 13:28

    This script should do. It's (almost) pure Bash. The seq part can be replaced if a completely pure bash is required.

    Since Bash apparently uses signed two-complement 4-byte integers, the script is limited to /8 mask maximum. I found ranges larger than /16 impractical anyway so this doesn't bother me at all. If someone knows a simple way to overcome this, please share :)

    #!/usr/bin/env bash
    
    base=${1%/*}
    masksize=${1#*/}
    
    [ $masksize -lt 8 ] && { echo "Max range is /8."; exit 1;}
    
    mask=$(( 0xFFFFFFFF << (32 - $masksize) ))
    
    IFS=. read a b c d <<< $base
    
    ip=$(( ($b << 16) + ($c << 8) + $d ))
    
    ipstart=$(( $ip & $mask ))
    ipend=$(( ($ipstart | ~$mask ) & 0x7FFFFFFF ))
    
    seq $ipstart $ipend | while read i; do
        echo $a.$(( ($i & 0xFF0000) >> 16 )).$(( ($i & 0xFF00) >> 8 )).$(( $i & 0x00FF ))
    done 
    

    Usage:

    ./script.sh 192.168.13.55/22
    

    Tested with Bash version 4.4.23. YMMV.

提交回复
热议问题