Whenever I try to use the ip2long() function, I get back a negative number. Whenever I use bindec() to convert a binary number to decimal, I get back a negative number as well. Is there someting wrong with my config, or am I not using these functions correctly?

Taken straight from the manual (http://php.net/manual/function.ip2long.php):
<?php
$ip = gethostbyname("www.php.net");
$out = "The following URLs are equivalent:<br>\n";
$out .= "http://www.php.net/, http://".$ip."/, and http://".ip2long($ip)."/<br>\n";
echo $out;
?>

The result for me is this: http://nemesis2.com/testdir/ip2long.php

I am using php-4.0.3pl1. Can anyone else verify that this function works or does not work for them?

Thanks,
Jason

    Did a search on the bugs page, came up with this:
    http://bugs.php.net/bugs.php?id=7248

    According to php.net: "It is meant to do so[return a negative number], PHP long values are signed."

    What does that mean? How do I get the actual number I want?

      dunno, i've never used the function before

      just pasted the output of what appeared from your code running on my webserver.

      debian linux (woody) kernel 2.2.17

      apache 2.2

        a year later

        IP addresses are 32-bits, unsigned. If you have, for example, 255.0.0.0 as your IP address, in binary notation it looks like this:

        11111111000000000000000000000000

        The problem is that PHP uses 32-bit, unsigned integers. The leftmost bit in an unsigned int, if == 1, indicates a number is negative. That's fine unless you're trying to manipulate IPs using PHPs... the larger numbers wrap around and become negative.

        It might help to do sprintf("%u",ip2long($whatever)). That will print the positive number you want.

        Hope that helps,

        Jason Signalness
        Systems Administrator, BTINet.

          Write a Reply...