Jump to content

Convert IP to integer and vice versa


chaking

Recommended Posts

Ok, so I know how to convert an IP address into an integer... like so:

 

IP: 10.11.12.13

 

$a = 10

$b = 11

$c = 12

$d = 13

 

($a * 256 to the third) + ($b * 256 squared) + ($c * 256) + ($d) = the integer

or

($a * 16777216) + ($b * 65536) + ($c * 256) + ($d) = the integer

 

Now, how do you take the final integer and and convert it back to a regular ip address with decimals and all?

Link to comment
https://forums.phpfreaks.com/topic/189244-convert-ip-to-integer-and-vice-versa/
Share on other sites

It's fairly easy.

 

<?php
function myip2long($ip)
{
list($o1,$o2,$o3,$o4) = explode('.', $ip);
return ($o1 << 24) + ($o2 << 16) + ($o3 <<  + $o4;
}

var_dump(myip2long('4.5.6.7'), ip2long('4.5.6.7'));

function mylong2ip($n)
{
return sprintf('%d.%d.%d.%d',
	$n >> 24,
	($n & 16711680) >> 16,
	($n & 65280) >> 8,
	$n & 255
);
}

var_dump(mylong2ip(67438087), long2ip(67438087));

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.