mavelite
Enthusiast
Enthusiast

Obtain next available external network IP

Jump to solution

Hello,

I am trying to automate the rollout of nested environments that will require external network connections. I'm looking for a way to determine the next available free IP from a given external networks IP pool. I can get the list of IP's from the pool, the total number used and total number free but have been unable to locate a method to show what's free next.

There must be a way to obtain this information as deploying a new Edge on an external network grabs the next available free IP.

Anyone have luck with this???

0 Kudos
1 Solution

Accepted Solutions
mavelite
Enthusiast
Enthusiast

Posted this to my Blog but here is the final code I came up with that works for my purposes.

http://www.justavmwblog.com/2015/05/vcloud-next-free-ip/

function Get-FreeExtIPAddress([String]$extnetName){

$extnet = Get-ExternalNetwork -name $extnetName

$ExtNetView = $Extnet | Get-CIView

$allocatedGatewayIPs = $extnetView.Configuration.IpScopes.IpScope[0].SubAllocations.SubAllocation.IpRanges.IpRange

[int]$ThirdStartingIP = [System.Convert]::ToInt32($extnet.StaticIPPool[0].FirstAddress.IPAddressToString.Split(".")[2],10)

[int]$ThirdEndingIP = [System.Convert]::ToInt32($extnet.StaticIPPool[0].LastAddress.IPAddressToString.Split(".")[2],10)

[int]$FourthStartingIP = [System.Convert]::ToInt32($extnet.StaticIPPool[0].FirstAddress.IPAddressToString.Split(".")[3],10)

[int]$FourthEndingIP = [System.Convert]::ToInt32($extnet.StaticIPPool[0].LastAddress.IPAddressToString.Split(".")[3],10)

$octet = $extnet.StaticIPPool[0].FirstAddress.IPAddressToString.split(".")

$3Octet = ($octet[0]+"."+$octet[1]+"."+$octet[2])

$2Octet = ($octet[0]+"."+$octet[1])

$ips = @()

if ($ThirdStartingIP -eq $ThirdEndingIP) {

$ips = $FourthStartingIP..$FourthEndingIP | % {$3Octet+'.'+$_}

} else {

do {

for ($i=$FourthStartingIP; $i -le 255; $i++) {

$ips += ($2Octet + "." + $ThirdStartingIP + "." + $i)

}

$ThirdStartingIP=$ThirdStartingIP + 1

} while ($ThirdEndingIP -ne $ThirdStartingIP)

for ($i=0;$i -le $FourthEndingIP; $i++) {

$ips += ($2Octet + "." + $ThirdStartingIP + "." + $i)

}

}

$allocatedIPs = $ExtNetView.Configuration.IpScopes.IpScope[0].AllocatedIpAddresses.IpAddress

for ($i=0;$i -le $ips.count; $i++) {

for ($j=0; $j -lt $allocatedGatewayIPs.count; $j++) {

if ($ips[$i] -eq $allocatedGatewayIPs[$j].StartAddress) {

$ips = $ips | Where-Object { $_ -ne $ips[$i] }

$i--

}

}

for($z=0;$z -lt $allocatedIPs.count;$z++) {

if ($ips[$i] -eq $allocatedIPs[$z]) {

$ips = $ips | Where-Object { $_ -ne $ips[$i] }

$i--

}

}

}

return $Ips

}

View solution in original post

0 Kudos
4 Replies
LucD
Leadership
Leadership

There is a good and simple script for that in PowerShell – find a free IP


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

mavelite
Enthusiast
Enthusiast

So that works if I just want to walk an entire subnet but when sub-allocating IP's to an edge they won't ping until they are actually used. I'm looking for a way to find the next available and free IP that has not been sub-allocated to an Edge.

When you go to deploy a new Edge it pulls the next available unused IP, I'm looking to do the same thing.

Mav

0 Kudos
bdmpastx
Contributor
Contributor

function Get-FreeExtIPAddress{

Param (
    $DataCenter
    )
Process{

    #========================================================================
#SUB Function search the 3rd Octet
#========================================================================
    Function Search-IP-3rdOct {
        Param (
            [int]$StartSearchNumber,
            [int]$EndSearchNumber,
            $IPArray )
        Process {
            $IPSearchComplete = $false

            do {
                :outerLoop
                For ($i = $StartSearchNumber; $i -le $EndSearchNumber; $i++){
                    Write-Log "--Searching Subnet: $i"
                    #Build an array of IP's in the $i subnet     
                    [int[]] $allocatedIPsLastOcts = @()           
                    $existingIPs = @($IPArray | where {($_ -split "\.")[2] -eq $i})
                    foreach ($existingIP in $existingIPs) {
                     $allocatedIPsLastOcts += ($existingIP -split "\.")[3]
                    }
                          
                 $allocatedIPsLastOcts = $allocatedIPsLastOcts | Sort
                 #$FreeIP = Search-Subnet -allocatedIPsLastOct $allocatedIPsLastOcts
   
                    $mylastOctIP = 4   
                    $EmptyLastOctIP = 0
                 foreach ($allocatedIPsLastOct in $allocatedIPsLastOcts) {
                  if (!$mylastOctIP) {
                   $mylastOctIP = $allocatedIPsLastOct
                  }
                  $myIPdifference = ($allocatedIPsLastOct - $mylastOctIP)
                  #search for the hole. if difference is Greater than one, we found a hole
                  if ($myIPdifference -gt 1) {
                   $EmptyLastOctIP = ($mylastOctIP + 1)
                            $IPAddressToAdd = ($existingIPs[0] -split "\.")[0] + "." + ($existingIPs[0] -split "\.")[1] + "."+$i+"." + ($EmptyLastOctIP)
                      Write-Host "`tFound IP in $i subnet: $IPAddressToAdd"
                      Write-Log "Found IP in $i subnet: $IPAddressToAdd"
                   $IPSearchComplete = $true
                            break outerLoop
                  }
                  $mylastOctIP = $allocatedIPsLastOct
                 }
                 if ($EmptyLastOctIP -eq 0){
                        #we didn't find any holes but the subnet might not be full
                  if ($mylastOctIP -le 254){
                   $EmptyLastOctIP = $mylastOctIP + 1
                            $IPAddressToAdd = ($existingIPs[0] -split "\.")[0] + "." + ($existingIPs[0] -split "\.")[1] + "."+$i+"." + ($EmptyLastOctIP)
                      Write-Host "`tFound IP in $i $IPAddressToAdd"
                      Write-Log "Found IP in $i $IPAddressToAdd"
                            $IPSearchComplete = $true
                            break outerLoop
  
                  }
                  else{
                   $EmptyLastOctIP = 0
                            $IPAddressToAdd = $null
                      write-host "`tIP Subnet $i is Full"
                  }
                 }
                }
                $IPAddressToAdd
            }
            until($IPSearchComplete)
        }
    }

    #========================================================================
#SUB Function search a particular subnet
#========================================================================
    Function Search-Subnet{
     Param (
            $allocatedIPsLastOct
        )
        Process {
      #$mycount = 1
      #$subnetsearch = $false
            $EmptyIP = 0
      foreach ($allocatedIP in $allocatedIPsLastOct) {
       if (!$mylastIP) {
        $mylastIP = $allocatedIP
       }
       $mycurrentIP = $allocatedIP
       $myIPdifference = ($mycurrentIP - $mylastIP)
  
       #write-host "$mycurrentIP - $mylastIP = $myIPdifference"
       #search for the hole. if difference is Greater than one, we found a hole
       if ($myIPdifference -gt 1) {
        $EmptyIP = ($mylastIP + 1)
                    $EmptyIP
        #write-host "Found empty IP: $EmptyIP"
        break
       }
       $mylastIP = $allocatedIP
      }
      if ($EmptyIP -eq 0){
       #write-host "No Holes Found"
       if ($mylastIP -le 254){
        $EmptyIP = $mylastIP+1
                    $EmptyIP
        #write-host "Found empty IP: $EmptyIP"
       }
       else{
        $EmptyIP = 0
                    $EmptyIP
        write-host "`tIP Subnet is Full"
       }
      }
     }
    }


#========================================================================
# MAIN Code
#========================================================================
Write-Host "`nSearching for the next free IP Address" -ForegroundColor 'Cyan'
Write-Host "-----------------------------------------------------"
    write-host "Data Center:`t" $DataCenter
    Write-Host "-----------------------------------------------------"
Write-Log "--IPaddress search starting"
# Find the next available IP address
$IPExtractOK = $false 
    $manualIPOK = $false 

    $count = 0
do {
  try{
           
   $extnet = Get-ExternalNetwork
            $ExtNetView = $Extnet | Get-CIView
            $allocatedIPs = $extnetView.Configuration.IpScopes.IpScope[0].allocatedipaddresses.ipaddress
   
   $IPCount = ($allocatedIPs | measure).Count
   write-host "--Found $IPCount IP Addresses in use"
   $error.clear()
   $IPExtractOK = $true
  }
  catch{
            $count++
   write-host "--An error has occurred whilst collecting the used IP addresses"  -foregroundcolor Red
   write-host $error -foregroundcolor Red
   #if count is over 3, try and reconnect the server
            if ($count -ge 1){
                write-host "--IP collection has failed repeatedly... " -foregroundcolor yellow
                $IPAddressToAdd = read-host "Enter an IP address to use"
                $error.clear()
                $manualIPOK = $true
                break
            }

            write-host "--Script will try and recollect the IP's in 5 seconds time..."  -foregroundcolor yellow
   start-sleep -seconds 5
   $IPExtractOK = $false
            $error.clear()
  }
}
until($IPExtractOK -or $manualIPOK)

#We have 3 datacenters so we have it search based off of it. You can remove this and replace the code with the variables with hard coded figures if you want

if ($IPExtractOK){
        if($DataCenter -eq "yourdatacenter"){
            $StartOct = $DefinitionyourdatacenterStartIP.Split(".")[2]
            $EndOct = $DefinitionyourdatacenterEndIP.Split(".")[2]
            $IPAddressToAdd = Search-IP-3rdOct -StartSearchNumber $StartOct -EndSearchNumber $EndOct -IPArray $allocatedIPs
        }
        elseif($DataCenter -eq "yourdatacenter"){
            $StartOct = $DefinitionyourdatacenterStartIP.Split(".")[2]
            $EndOct = $DefinitionyourdatacenterEndIP.Split(".")[2]
            $IPAddressToAdd = Search-IP-3rdOct -StartSearchNumber $StartOct -EndSearchNumber $EndOct -IPArray $allocatedIPs
        }
        elseif($DataCenter -eq "yourdatacenter"){
            $StartOct = $DefinitionyourdatacenterStartIP.Split(".")[2]
            $EndOct = $DefinitionyourdatacenterEndIP.Split(".")[2]
            $IPAddressToAdd = Search-IP-3rdOct -StartSearchNumber $StartOct -EndSearchNumber $EndOct -IPArray $allocatedIPs
        }
    }

if (!$IPAddressToAdd){
        $IPAddressToAdd = "0.0.0.0"
  Write-Host "ERROR: No IP Found" -ForegroundColor red
  Write-Log "ERROR: No IP Found"
        $x = Read-host "`nPress ENTER to continue ..."
  exit
}

    if ($error){
  Write-Log "ERROR:"
  Write-Log $error
        Write-Host "ERROR FOUND" -foregroundcolor Red
        $x = Read-host "`nPress ENTER to continue ..."
  $error.clear()
}

$IPAddressToAdd
Write-Host "--The next free IP is: "$IPAddressToAdd
Write-Host "--This will be used as the external IP for this org"
Write-Host "--IP Address search complete" -ForegroundColor 'Green'
Write-Log "The next free IP is: $IPAddressToAdd"
Write-Log "--IP Address search complete"

    }
}

0 Kudos
mavelite
Enthusiast
Enthusiast

Posted this to my Blog but here is the final code I came up with that works for my purposes.

http://www.justavmwblog.com/2015/05/vcloud-next-free-ip/

function Get-FreeExtIPAddress([String]$extnetName){

$extnet = Get-ExternalNetwork -name $extnetName

$ExtNetView = $Extnet | Get-CIView

$allocatedGatewayIPs = $extnetView.Configuration.IpScopes.IpScope[0].SubAllocations.SubAllocation.IpRanges.IpRange

[int]$ThirdStartingIP = [System.Convert]::ToInt32($extnet.StaticIPPool[0].FirstAddress.IPAddressToString.Split(".")[2],10)

[int]$ThirdEndingIP = [System.Convert]::ToInt32($extnet.StaticIPPool[0].LastAddress.IPAddressToString.Split(".")[2],10)

[int]$FourthStartingIP = [System.Convert]::ToInt32($extnet.StaticIPPool[0].FirstAddress.IPAddressToString.Split(".")[3],10)

[int]$FourthEndingIP = [System.Convert]::ToInt32($extnet.StaticIPPool[0].LastAddress.IPAddressToString.Split(".")[3],10)

$octet = $extnet.StaticIPPool[0].FirstAddress.IPAddressToString.split(".")

$3Octet = ($octet[0]+"."+$octet[1]+"."+$octet[2])

$2Octet = ($octet[0]+"."+$octet[1])

$ips = @()

if ($ThirdStartingIP -eq $ThirdEndingIP) {

$ips = $FourthStartingIP..$FourthEndingIP | % {$3Octet+'.'+$_}

} else {

do {

for ($i=$FourthStartingIP; $i -le 255; $i++) {

$ips += ($2Octet + "." + $ThirdStartingIP + "." + $i)

}

$ThirdStartingIP=$ThirdStartingIP + 1

} while ($ThirdEndingIP -ne $ThirdStartingIP)

for ($i=0;$i -le $FourthEndingIP; $i++) {

$ips += ($2Octet + "." + $ThirdStartingIP + "." + $i)

}

}

$allocatedIPs = $ExtNetView.Configuration.IpScopes.IpScope[0].AllocatedIpAddresses.IpAddress

for ($i=0;$i -le $ips.count; $i++) {

for ($j=0; $j -lt $allocatedGatewayIPs.count; $j++) {

if ($ips[$i] -eq $allocatedGatewayIPs[$j].StartAddress) {

$ips = $ips | Where-Object { $_ -ne $ips[$i] }

$i--

}

}

for($z=0;$z -lt $allocatedIPs.count;$z++) {

if ($ips[$i] -eq $allocatedIPs[$z]) {

$ips = $ips | Where-Object { $_ -ne $ips[$i] }

$i--

}

}

}

return $Ips

}

View solution in original post

0 Kudos