powershellgeolocationipgeoipip2location

Error converting IP number to IP address from ip2location database?


I have downloaded ip2location database in csv format and reading 1st column data and converting IP number into IP address using below code as suggested in ip2location FAQ.

Sample CSV Data:

enter image description here

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

    try
    {    
        $w = [int]($number/16777216)%256
        $x = [int]($number/65536)%256
        $y = [int]($number/256)%256
        $z = [int]$number%256

        $ipAddress = "$w.$x.$y.$z"
        Write-Host "Actual IP Address - $ipAddress"

        Write-Host "Returning IP Address"
        return $ipAddress
    }
    catch
    {
        throw $_
    }
}

Convert-NumbetToIP -number 2147483648

But get below error Cannot convert value "2147483648" to type "System.Int32". Error: "Value was either too large or too small for an Int32."

Can someone help me to to get the correct IP address also please let me know what type of data is in 2nd column.


Solution

  • I have found the answer by changing the [int] to [int64]

    function Convert-NumbetToIP
    {
        param(
        [Parameter(Mandatory=$true)][string]$number
        )
    
        try
        {    
            $w = [int64]($number/16777216)%256
            $x = [int64]($number/65536)%256
            $y = [int64]($number/256)%256
            $z = [int64]$number%256
    
            $ipAddress = "$w.$x.$y.$z"
            Write-Host "Actual IP Address - $ipAddress"
    
            Write-Host "Returning IP Address"
            return $ipAddress
        }
        catch
        {
            throw $_
        }
    }
    
    Convert-NumbetToIP -number 2147483648