Perl script to allocate next available IP from a range

Hi

I am looking to automate the process in PERL of allocating IP addresses from a set range of addresses (for example a /22 network 10.10.224.1 - 10.10.227.254)

I am able to query the IP addresses that are already in use in the above range, which will produce me a list like this for example

10.10.224.1
10.10.224.2
10.10.224.3
10.10.225.23
10.10.225.35
10.10.227.67
...
...

What I am trying to do is find a way of taking that list and determining the next available IP address for use within the boundaries of the netmask (so for example between 10.10.224.1 and 10.10.227.254) Naturally if this was just a standard list of numbers then it would be straightforward, but given they are IP addresses, its a bit more complex

does anyone know a good starting point for this or have any experience of setting up something similar?

Cheers

How do you supply the netmask? What be the desired output from above ( 10.10.224.4 or 10.10.227.68 )?

Hi RudiC, at the moment I am starting from scratch. I will probably define the network I want to allocate against within the script, or maybe pass it in as an argument... either way, lets assume I have a 10.10.224.0/22 network (as an example) ... within the script I can already populate an array with the 'used' IP's in that range ... but my challenge is to find away of evaluating the ones that arent in use (free to use) within that range.

Sorry, but im not sure I understand the 2nd part of your question with those IPs you have given

If you got bash , copy this

while read LINE
  do    IP=$((0x$(printf "%02X" ${LINE//./ })));
        if (( INITDONE == 0 ))
          then  NETMASK=$(( (2**32-1)-(2**(32-$2)-1) ));
                ORG=$((IP & NETMASK));
                NXTSUB=$(( ORG + 2**(32-$2) ))
                INITDONE=1
          fi
        if (( IP != ${NXTIP:-$IP} ))
          then  printf "next free IP: %d.%d.%d.%d\n" $((NXTIP>>24)) $((NXTIP>>16&255)) $((NXTIP>>8&255)) $((NXTIP&255))
                break
          fi
        NXTIP=$(( ++IP ))
        if (( NXTIP >= NXTSUB ))
          then  printf "no free IP in subnet\n"
                break
          fi    
  done < $1

into a script file, make it executable and run it like

./script IPfile 22

with IPfile containig your above example.

1 Like