Search code examples
powershellip

Powershell IP address range


I need to help with my code which is write in Powershell. Program should generate IP addresses in range. For example from 10.4.254.250 to 10.4.255.255.

When I have the same subnet (from 10.4.255.x to 10.4.255.x), all is correct. Problem starts when I have different subnet (from 10.4.254.250 to 10.4.255.255).

Output is invalid. Try it please. Thank you, for your help.

Correct output should be, that ip address which is 10.4.255.X starts from 1. Now starts from 250 to 255.

I need to get all ip addresses from variable $from to variable $to. When IP address in the same subnet $from = "10.4.255.1" $to = "10.4.255.1" all is correct. Problem starts, when different subnet $from = "10.4.254.250" $to = "10.4.255.255"

Look at my code bellow:

$from = "10.4.254.250"
$to = "10.4.255.255"

$Ip_Adresa_Od = $from -split "\."
$Ip_Adresa_Do = $to -split "\."

foreach ($Ip_Adresa_A in $Ip_Adresa_Od[0]..$Ip_Adresa_Do[0])
{
    foreach ($Ip_Adresa_B in $Ip_Adresa_Od[1]..$Ip_Adresa_Do[1])
    {
        foreach ($Ip_Adresa_C in $Ip_Adresa_Od[2]..$Ip_Adresa_Do[2])
        {
            foreach ($Ip_Adresa_D in $Ip_Adresa_Od[3]..$Ip_Adresa_Do[3])
            {
                $Ip_Adresa_Pocitace = "$Ip_Adresa_A.$Ip_Adresa_B.$Ip_Adresa_C.$Ip_Adresa_D"
                $Ip_Adresa_Pocitace
            }
        }
    }
}

Wrong output is:

10.4.254.250
10.4.254.251
10.4.254.252
10.4.254.253
10.4.254.254
10.4.254.255
10.4.255.250
10.4.255.251
10.4.255.252
10.4.255.253
10.4.255.254
10.4.255.255

Solution

  • You have to convert your IP address to an integer and then in each iteration of a for loop convert the integer to a byte array:

    $from = "10.4.254.250"
    $to = "10.4.255.255"
    
    $Ip_Adresa_Od = $from -split "\."
    $Ip_Adresa_Do = $to -split "\."
    
    #change endianness
    [array]::Reverse($Ip_Adresa_Od)
    [array]::Reverse($Ip_Adresa_Do)
    
    #convert octets to integer
    $start=[bitconverter]::ToUInt32([byte[]]$Ip_Adresa_Od,0)
    $end=[bitconverter]::ToUInt32([byte[]]$Ip_Adresa_Do,0)
    
    for ($ip=$start; $ip -lt $end; $ip++)
    { 
        #convert integer back to byte array
        $get_ip=[bitconverter]::getbytes($ip)
    
        #change endianness
        [array]::Reverse($get_ip)
    
        $new_ip=$get_ip -join "."
        $new_ip
    }