Home > Enterprise >  What is the correct IP address conversion from number?
What is the correct IP address conversion from number?

Time:02-01

I am trying to convert number into IP address using powershell method and checking same online, I am getting 2 different result.

Example:

number = 16812043
result1 = 11.136.0.1 #using powershell
result2 = 1.0.136.11 #https://codebeautify.org/decimal-to-ip-converter

I have tried below code

function Convert-NumberToIP
{
    param(
        [Parameter(Mandatory=$true)][string]$number
    )

    [Int64] $numberInt = 0
    
    if([Int64]::TryParse($number, [ref]$numberInt))
    {
        if(($numberInt -ge 0) -and ($numberInt -le 0xFFFFFFFFl))
        {
            ([IPAddress] $numberInt).ToString()
        }
    }
}

Convert-NumberToIP -number 16812043

I am getting 2 different result not sure which 1 is correct, or should I update the function.

CodePudding user response:

This is how your function should look, instead of using [Int64]::TryParse(...) you can simply use [ipaddress]::TryParse(...):

function Convert-NumberToIP {
    param(
        [Parameter(Mandatory=$true)]
        [string] $Number
    )

    $ref = [ref] [ipaddress]::Any

    if([ipaddress]::TryParse($Number, $ref)) {
        $ref.Value.ToString()
    }
}

Convert-NumberToIP -Number 16812043 # => 1.0.136.11

CodePudding user response:

Use the IPAddress.NetworkToHostOrder() method to flip the endianness of the octets represented by your decimal number:

PS ~> [ipaddress]::new([ipaddress]::NetworkToHostOrder(16812043)).IPAddressToString
1.0.136.11
  • Related