# 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:

``````
{
return 0;
} else {
return (\$ips + \$ips * 256 + \$ips * 256 * 256 + \$ips * 256 * 256 * 256);
}
}
``````

Convert IP address to integer with ASP:

``````
Dim i, pos, PrevPos, num
Else
For i = 1 To 4
pos = InStr(PrevPos + 1, IPaddress, ".", 1)
If i = 4 Then
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:

``````
{
int i;
string [] arrDec;
double num = 0;
{
return 0;
}
else
{
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

``````
Dim arrDec() As String
Dim i As Integer
Dim intResult As Long
Else
For i = arrDec.Length - 1 To 0 Step -1
intResult = intResult + ((Int(arrDec(i)) Mod 256) * Math.Pow(256, 3 -i))
Next
End If
End Function
``````

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 + \$ips * 256 + \$ips * 65536 + \$ips * 16777216); } } ```

2. ASP could be improved by doing this
``` Function IPAddressToNumber(IPaddress) If IPaddress = "" Then IPAddressToNumber = 0 Else ips = Split(IPAddress,".") IPAddressToNumber = ((ips)+(ips*256)+(ips * 65536)+(ips * 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))+(int.Parse(arrDec)*256)+(int.Parse(arrDec)*65536)+(int.Parse(arrDec)*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))+(int.Parse(arrDec)*256) +(int.Parse(arrDec)*65536)+(int.Parse(arrDec)*16777216)); } return num; } ```

Sorry Bout that

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

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. 8. PHP is the easiest way!

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

10. 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. In PHP, this can be done more simply, like this:

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

12. 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. @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. 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. 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. […] Justin-Cook.com, here is converting an existing String to […]

17. 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 << 24 ) | ( \$ip << 16 ) | ( \$ip << 8 ) | \$ip;
}

18. SQL/MySQL Anyone?

DELIMITER \$\$

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

RETURN CONCAT_WS('.',

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 +

END \$\$

DELIMITER ;

19. 20. 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

21. […] æˆ‘å‘çŽ°é€šè¿‡è°·æ­Œçš„ä¸€äº›ä¾‹å­ï¼Œåƒè¿™ä¸€ä¸ªæˆ– è¿™ä¸€ä¸ª ï¼Œä½†æˆ‘æ•¢è‚¯å®šåº”è¯¥æœ‰ä¸€ä¸ªæ ‡å‡†çš„æ–¹å¼æ¥å®žçŽ°è¿™ä¸€ç›®æ ‡ä½¿ç”¨ã€‚NETã€‚å”¯ä¸€çš„é—®é¢˜æ˜¯ï¼Œæˆ‘æ— æ³•æ‰¾åˆ°è¿™ä¸ªæ ‡å‡†çš„æ–¹æ³•ã€‚ç„¶åŽæˆ‘ä»¬å¯åŠ¨ä¼¼ä¹Žæ˜¯åœ¨æœç€æ­£ç¡®çš„æ–¹å‘ï¼Œä½†å®ƒä¸æä¾›ä»»ä½•èŽ·å¾—ä¸€ä¸ª'UINTçš„'ä»£è¡¨äº†… […]

22. 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)
23. 24. 