ASP Code, ASP.Net Code, PHP Code

Convert an IP address to IP number with PHP, ASP, C# and VB.Net

So you've retrieved the visitor's IP address. If you're just logging or tracing it, that's all you need to do. However, if you want to match it to an IP location database, you can't search by the IP in the IPV4 format. It needs to be converted to its IP number equivalent (it is just more efficient to store and search between a range of numbers in database). Here are the functions in PHP, ASP, C# and VB.Net to convert and IP address from dot format to IP number format.

Each function is based on the fact that IP addresses (IPV4) are divided into 4 sub-blocks. Each sub-block has a different weight number, each powered by 256. Here's the math:

IP Number = (16777216*a) + (65536*b) + (256*c) + (d (1))
– where the IP Address = a.b.c.d

And here are the functions that implement that math:

Convert with PHP:


function ip_address_to_number($IPaddress)
{
    if ($IPaddress == "") {
        return 0;
    } else {
        $ips = split ("\.", "$IPaddress");
        return ($ips[3] + $ips[2] * 256 + $ips[1] * 256 * 256 + $ips[0] * 256 * 256 * 256);
    }
}

Convert IP address to integer with ASP:


Function IPAddressToNumber(IPaddress)
  Dim i, pos, PrevPos, num
  If IPaddress = "" Then
    IPAddressToNumber = 0
  Else
    For i = 1 To 4
        pos = InStr(PrevPos + 1, IPaddress, ".", 1)
        If i = 4 Then 
            pos = Len(IPaddress) + 1
        End If
        num = Int(Mid(IPaddress, PrevPos + 1, pos - PrevPos - 1))
        PrevPos = pos
        IPAddressToNumber = ((num Mod 256) * (256 ^ (4 - i))) + IPAddressToNumber
    Next
  End If
End Function

Here's the C# code:


public double IPAddressToNumber(string IPaddress)
{
    int i;
    string [] arrDec;
    double num = 0;
    if (IPaddress == "")
    {
       return 0;
    }
    else
    {
       arrDec = IPaddress.Split('.');
       for(i = arrDec.Length - 1; i >= 0 ; i --)
       {
          num += ((int.Parse(arrDec[i])%256) * Math.Pow(256 ,(3 - i )));
       }
       return num;
    }
}

And here's the VB.NET function to convert an IP address to IP number


Public Function IPAddressToNumber(ByVal IPaddress As String) As Double
    Dim arrDec() As String
    Dim i As Integer
    Dim intResult As Long
    If IPaddress = "" then
       IPAddressToNumber = 0
    Else
       arrDec = IPaddress.Split(".")
       For i = arrDec.Length - 1 To 0 Step -1
          intResult = intResult + ((Int(arrDec(i)) Mod 256) * Math.Pow(256, 3 -i))
       Next
       IPAddressToNumber = intResult
    End If
End Function
Share

24 Comments

  1. Thank you for sharing this.

    Here is a small performance improvement to the PHP version:
    function ip_address_to_number($IPaddress) {
    if ($IPaddress == '') {
    return 0;
    } else {
    $ips = explode('.', $IPaddress);
    return ($ips[3] + $ips[2] * 256 + $ips[1] * 65536 + $ips[0] * 16777216);
    }
    }

  2. ASP could be improved by doing this

    Function IPAddressToNumber(IPaddress)
    If IPaddress = "" Then
    IPAddressToNumber = 0
    Else
    ips = Split(IPAddress,".")
    IPAddressToNumber = ((ips[3])+(ips[2]*256)+(ips[1] * 65536)+(ips[0] * 16777216))
    End If
    End Function

  3. Likewise the C# could look a bit more like this


    public double IPAddressToNumber(string IPaddress)
    {
    string [] arrDec;
    int num = 0;
    if (IPaddress != "")
    {
    arrDec = IPaddress.Split('.');
    num = (int.Parse(arrDec[3]))+(int.Parse(arrDec[2])*256)+(int.Parse(arrDec[1])*65536)+(int.Parse(arrDec[0])*16777216));
    }
    return num;
    }

  4. of course the last one won't work


    public int IPAddressToNumber(string IPaddress)
    {
    string [] arrDec;
    int num = 0;
    if (IPaddress != "")
    {
    arrDec = IPaddress.Split('.');
    num = (int.Parse(arrDec[3]))+(int.Parse(arrDec[2])*256)
    +(int.Parse(arrDec[1])*65536)+(int.Parse(arrDec[0])*16777216));
    }
    return num;
    }

    Sorry Bout that

  5. No need to reinvent the wheel — the .NET Framework already does this:

    Shared Function IPAddressToNumber(ByVal IPAddress As String) As Long
    Return System.Net.IPAddress.Parse(IPAddress).Address
    End Function

    Note also, an Integer is signed, trying to convert, say "128.0.0.1" will cause an arithmetic overflow exception unless you use a Long.

    &H80000001 is a negative number

  6. WOW cool thanks! I was looking how to do this in PHP for ages. 😀

  7. PHP is the easiest way!

  8. Your code is redundant for PHP – what Metin said, this function is built in to PHP – see http://www.php.net/ip2long

  9. Apart from the fact that the PHP method being redundant, your code gives differing values from the actual ones which should occur. For example, the IP address 212.58.240.0 equates to 3560632320 with your method, but i actually -734334976 everywhere else. In fact, your code will never produce a negative number, which an actual IP Number can be.

  10. In PHP, this can be done more simply, like this:

    function ip_address_to_number( $IPAddress )
    {
    return sprintf("%010u", ip2long( $IPAddress ) );
    }

  11. The Net call: System.Net.IPAddress.Parse(IPAddress).Address has been deprecated by Microsoft in VS 2008 due to being extremely buggy. It won't correctly handle quite a few addresses.

  12. @Ashley Sheridan

    This is incorrect, a negative numbered IP number is simply an indication that the wrong datatype is being used to store it.
    IP Addresses are actually a 32bit binary number, in decimal these are values between 0 (0.0.0.0) and 4294967295 (255.255.255.255)

    On 32Bit Computer Systems (i.e. most PCs & servers out there today), an UNSIGNED integer value has the range 0-4294967295. A SIGNED Interger will have the range −2147483648 to +2147483647. This is because 1 bit is "Wasted" as the sign.

    However PHP (for reasons that are completely beyond me) doesn't support unsigned integers. For this reason, IP numbers in PHP *should* be stored as FLOATs AKA DOUBLEs

    However, PHPs ip2long function returns a signed integer value, rather that the long value implied. This means that any IP address higher than 127.255.255.255 gets a negative value, which is incorrect.

    The following function returns a properly formatted float.

    function myip2long($ip){
    return floatval(sprintf("%u",ip2long('$ip')));
    }

    @Ben Faust

    Your function returns the number as a string value, instead of a number, (not a big problem in PHP I know) but why do you pad the result out to 10 digits with 0's ?

  13. thanks jocker… it was the long pending heart-ache for me… that i couldn't get it solved by using long2ip() php function… ur code worked fantastic… and special thanks to JUSTIN COOK too… thanks buddy…

  14. PHP reverse function ( Number to IP )

    function number2ip($number){
    $oct4 = ($number – fmod($number,16777216)) / 16777216;
    $oct3 = (fmod($number,16777216) – (fmod($number,16777216) % 65536)) / 65536;
    $oct2 = (fmod($number,16777216) % 65536 – (fmod($number , 16777216) % 65536 % 256)) / 256;
    $oct1 = fmod($number , 16777216) % 65536 % 256;
    $ip = $oct1 . "." . $oct2 . "." . $oct3 . "." . $oct4;
    return $ip;
    }

  15. Java - IP Address to Integer and back « Teneo !!!

    […] Justin-Cook.com, here is converting an existing String to […]

  16. Those 256 * 256 * 256 always make me laugh. Here's a PHP version that's roughly 2 times faster than the one in the post. And yes, I'm aware of ip2long.

    function ip2num( $ip )
    {
    if ( empty( $ip ) ) return 0;
    $ip = explode( '.', $ip );

    return ( $ip[0] << 24 ) | ( $ip[1] << 16 ) | ( $ip[2] << 8 ) | $ip[3];
    }

  17. SQL/MySQL Anyone?

    DELIMITER $$

    DROP FUNCTION IF EXISTS `__schema__`.`INT2IP` $$
    CREATE FUNCTION `__schema__`.`INT2IP` ( address INT UNSIGNED ) RETURNS VARCHAR(15)
    BEGIN

    RETURN CONCAT_WS('.',
    address >> 24 & 255,
    address >> 16 & 255,
    address >> 8 & 255,
    address & 255 );

    END $$

    DROP FUNCTION IF EXISTS `__schema__`.`IP2INT` $$
    CREATE FUNCTION `__schema__`.`IP2INT` ( address VARCHAR(15) ) RETURNS INT UNSIGNED
    BEGIN

    RETURN
    SUBSTRING_INDEX( address, '.', 1 ) * 16777216 +
    SUBSTRING_INDEX( SUBSTRING_INDEX( address, '.', 2 ),'.',-1 ) * 65536 +
    SUBSTRING_INDEX( SUBSTRING_INDEX( address, '.', -2 ),'.',1 ) * 256 +
    SUBSTRING_INDEX( address, '.', -1 );

    END $$

    DELIMITER ;

  18. can anyone say how to parse an ip address using java?
    for eg:if the ip address is 121.172.123.133 means i have to take only upto 121.172.123

  19. 你如何在C#中解析的IP地址字符串? | IT技术问答论坛IT技术问答论坛

    […] 我发现通过谷歌的一些例子,像这一个或 这一个 ,但我敢肯定应该有一个标准的方式来实现这一目标使用。NET。唯一的问题是,我无法找到这个标准的方法。然后我们启动似乎是在朝着正确的方向,但它不提供任何获得一个'UINTçš„'代表了… […]

  20. The algorythms given in this page doesn´t work in architecture of 32 bits. they don't return negative numbers, so they are't complete.
    For example:
    I want to convert 190.235.250.9 to number(if a use the algorythms from here, it would return 3203136009(worng answer)
    Right answer => -1091831287

  21. This posting kocenkd my socks off

Leave a Reply

Your email address will not be published. Required fields are marked *

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image