Search code examples
powershellipip-address

What is the correct IP address conversion from number?


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.


Solution

  • [IPAddress]::Parse() can parse out IP addresses from multiple data types (including integer or string)

    [Int] $ipInt = 16812043
    ([IPAddress]::Parse($ipInt) | Select -ExpandProperty IPAddressToString)
    

    Also, if you want to do the inverse (converting an IP address to a integer), can do this using the following...

    [String] $ipStr = '1.0.136.11'
    [IPAddress]::HostToNetworkOrder([BitConverter]::ToInt32([IPAddress]::Parse($ipStr).GetAddressBytes(), 0))