By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
437,949 Members | 1,855 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 437,949 IT Pros & Developers. It's quick & easy.

decimal to ip

P: 2
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>

[PHP]
<?
$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;
}

?>[/PHP]


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

have a nice day.
Feb 28 '07 #1
Share this Question
Share on Google+
2 Replies


P: 2
ehem... hi?
Mar 6 '07 #2

ronverdonk
Expert 2.5K+
P: 4,258
Your code works fine as far as outputting a dotted adress is concerned. Definitely not 0.0.0.0!
I don't think it is a valid IP address, but since it is your code you should know the algorithm to convert it correctly.

[php]
<?
$print_ip = dec2ip(1136272721);
// 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;
}

?>[/php]

Ronald :cool:
Mar 6 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.