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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.