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

10 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.

Leave a reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>

*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-Spam Image