简体   繁体   中英

How can I create with bash all the possible combinations of IPs?

This would be the output:

0.0.0.0
0.0.0.1
0.0.0.2
.
.
.
.
255.255.255.253
255.255.255.254
255.255.255.255

Maybe I will need to save it to a file, but I can easily do that with > operator

Well, if bash could handle it, this expression would do the trick:

echo {0..255}.{0..255}.{0..255}.{0..255} | tr ' ' \\n

But the above expression gets expanded by bash and the resulting 4 billion IP blows up the shell. Rather, you can just write nested loops like this:

for octet1 in {0..255}
do
  for octet2 in {0..255}
  do
    for octet3 in {0..255}
    do
      for octet4 in {0..255}
      do
        echo $octet1.$octet2.$octet3.$octet4
      done
    done
  done
done

You can also shorten this a bit like this:

for octet12 in {0..255}.{0..255}
do
  for octet34 in {0..255}.{0..255}
  do
    echo $octet12.$octet34
  done
done

In general, the bash language has sufficient power to manipulate IP addresses. I have a small set of functions I use for IP math that I can share with you for more general IPv4 work. Here's some code using my library of IP functions. TBH: I call it "my library" but I'm sure I lifted it from another developer years ago but I've lost the attribution.

So here's the code:

ip_range "0.0.0.0" "255.255.255.255" 1

And here's the set of functions:

#!/usr/bin/env bash

function ip2value() { 

local ip=$1 # IP address to convert to decimal
local sum=0

IFS='.' read -ra ADDR <<< "$ip"
for i in "${ADDR[@]}"; do
    sum=$(( sum * 256 + i )) 
done
echo $sum
}

function value2ip() { 

local value=$1
local ip=""
local divisor=$(( 256 ** 3 )) 

for x in 0 1 2  
do
    ip="$ip.$(( value / divisor ))"
    value=$(( value % divisor ))
    divisor=$(( divisor / 256 )) 
done

ip=${ip#.}
ip=$ip.$value
echo $ip
}


# Usage:  addIP <ip> [<count>]
# Increase <ip> by <count> ( default 1)
function nextIP() {
  local IP=$1
    local COUNT=$2
  : ${COUNT:=1}
    value2ip $(( $COUNT + $( ip2value $1 ) )) 
}

function addIPs() {
  local IP1=$1
  local IP2=$2

  value2ip $(( $( ip2value $IP1 ) + $( ip2value $IP2 ) ))
}

function isIP() {
  local IP=$1
  local VALUE=$( ip2value $IP )
  local VIP=$( value2ip $VALUE ) 

  [ "$IP" == "$VIP" ] 
}

function ip_range() { 
  local FIRST=$1
  local LAST=$2
  local STEP=$3

  : ${STEP:=1}

  local ip=$(ip2value $FIRST)
  local last=$(ip2value $LAST)

  while 
   [ $ip -le $last ] 
  do
   echo $( value2ip $ip )
   ip=$(( ip + 1 ))
  done
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM