IP range generator script [closed]

2019-01-15 11:56发布

问题:

I need a script that will generate IP ranges... lets say from 64.1.1.1 to 74.255.255.255 and the output should be like this:

64.1.1.1 
64.1.1.2
64.1.1.3
........
74.255.255.254
74.255.255.255
(line-by-line)

回答1:

#!/bin/bash

# convert IP to decimal
ip2dec() {
  set -- ${1//./ }     # split $1 with "." to $1 $2 $3 $4
  declare -i dec       # set integer attribute
  dec=$1*256*256*256+$2*256*256+$3*256+$4
  echo $dec
}

# convert decimal to IP
dec2ip() {
  declare -i ip1 ip2 ip3 ip4
  ip1=$1/256/256/256
  ip2=($1-$ip1*256*256*256)/256/256
  ip3=($1-$ip1*256*256*256-$ip2*256*256)/256
  ip4=$1-$ip1*256*256*256-$ip2*256*256-$ip3*256
  echo $ip1.$ip2.$ip3.$ip4
}

s=$(ip2dec $1)
e=$(ip2dec $2)

for ((i=$s;i<=$e;i++)); do
  dec2ip $i 
done

Example: ./script.sh 64.1.2.250 64.1.3.5

Output:

64.1.2.250
64.1.2.251
64.1.2.252
64.1.2.253
64.1.2.254
64.1.2.255
64.1.3.0
64.1.3.1
64.1.3.2
64.1.3.3
64.1.3.4
64.1.3.5

If you need performance, I suggest to use perl.



标签: bash unix ip