November 28th, 2006

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/Bookmark

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

Subscribe to comments with RSS or TrackBack to ' Convert an IP address to IP number with PHP, ASP, C# and VB.Net '.

  1. Jocker said,

    on January 2nd, 2007 at 5:57 am

    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. Ugot2BkidNme said,

    on January 5th, 2007 at 5:48 pm

    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. Ugot2BkidNme said,

    on January 5th, 2007 at 5:58 pm

    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. Ugot2BkidNme said,

    on January 5th, 2007 at 6:00 pm

    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. helper said,

    on March 27th, 2007 at 12:51 pm

    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. Joe said,

    on April 11th, 2007 at 7:49 pm

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

  7. Metin Kapçak said,

    on May 15th, 2007 at 4:59 am

    http://www.php.net/ip2long

  8. massoud said,

    on July 17th, 2007 at 6:54 am

    PHP is the easiest way!

  9. anon said,

    on October 27th, 2007 at 2:58 am

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


  10. on April 21st, 2008 at 4:45 am

    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.

  11. Ben Faust said,

    on July 29th, 2008 at 4:40 pm

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

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

  12. Randall Spychalla said,

    on September 16th, 2008 at 10:44 am

    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.

  13. Nick Critten said,

    on September 25th, 2008 at 7:19 am

    @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 ?

  14. bharadwaj said,

    on October 14th, 2008 at 2:15 am

    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…

  15. Will Smith said,

    on October 29th, 2008 at 10:47 am

    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;
    }


  16. on December 23rd, 2008 at 1:10 pm

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

  17. pim said,

    on February 13th, 2009 at 8:09 am

    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];
    }

  18. Josh said,

    on August 4th, 2009 at 7:58 am

    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 ;

  19. Jack said,

    on August 11th, 2009 at 9:51 am

    See similar converter in action at http://www.webtoolhub.com/tn561377-ip-address-number-converter.aspx

Leave a reply

*
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.
Click to hear an audio file of the anti-spam word