Jump to content

decimal ip to a real ip


nachotico

Recommended Posts

hi i'm new using PHP

 

here is what i need> i have a MySQL database that contain Decimal IPs -- the issue is that i don't know how to after extract them convert them to a real IP.

 

here is what i have for the moment>

 

<?
$print_ip = dec2ip($row[ip1]);
// where the ip should go into a table
echo "<td> $print_ip </td>";

/// here is the function decimal to ip
function dec2ip($dec) 
{
  if($dec>0) 
  {
   $dec=(double) 4294967296+$dec;
  }
  if($dec>16777215) 
  {
   $ip=$dec-(intval($dec/256)*256);
   $dec=(double) intval($dec/256);
  } 
  else $ip="0";
  if($dec>65535) 
  {
   $ip=($dec-(intval($dec/256)*256)).".".$ip;
   $dec=(double) intval($dec/256);
  } 
  else $ip="0.".$ip;
  if($dec<255) 
  {
   $ip=($dec-(intval($dec/256)*256)).".".$ip;
   $dec=(double) intval($dec/256);
  } 
  else $ip="0.".$ip;
  $ip=$dec.".".$ip;
  return (string) $ip;
}

?>

 

/// the result is this:

0.0.0.0

but when i don't call the function the Decimal looks like this

1136272721

so it's printing the decimal but the function to convert it to a real IP is not working well.

it should look like 89.255.25.25 *(not real ofc)

have a nice day.  Ty.

Link to comment
https://forums.phpfreaks.com/topic/40466-decimal-ip-to-a-real-ip/
Share on other sites

Try this function instead of your's

<?php
function dec2ip($dec) {
	settype($dec, float);
	$tmphex = sprintf("%08X",$dec);
	$hex_chunks = explode(',',chunk_split($tmphex,2,','));
	$dec_chunks = array();
	for($i=0;$i<4;$i++)
		$dec_chunks[$i] = hexdec($hex_chunks[$i]);
	return (implode('.',$dec_chunks));
}
?>

 

I created from the method of converting decimal IPs to dotted decimal IPs that I found on http://www.islandgraphicart.co.uk/php/decimal.php3

 

Ken

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.