Reputation: 13
I stubled upon following question:
"What is the output of the following code?"
echo long2ip(ip2long("127.0.255"));
The correct answer is: "127.0.255.0".
While it seems logical as this behavior is mentioned in the php manual and has even an example in the german manual, I have my issues reproducing it.
My code produces following outputs:
echo ip2long("127.0.255"); // outputs: FALSE
echo long2ip(ip2long("127.0.255")); //outputs: 0.0.0.0
The machine I tested this on has following software versions:
None of my colleagues could give me a precise explanation. The only assumption we have is, that it could be a conflict with the Suhosin-Patch.
If you have an explanation, please let me know.
Upvotes: 1
Views: 448
Reputation: 26
I have looked up the PHP source code of ip2long.
If inet_pton is available, inet_pton is used. Else inet_addr is used.
inet_pton checks, if the ip has the format ddd.ddd.ddd.ddd else it returns 0. http://man7.org/linux/man-pages/man3/inet_pton.3.html
if inet_addr is used, then missing parts of the ip are filled up with 0.
Upvotes: 1
Reputation: 23777
The PHP manual also states (https://www.php.net/manual/en/function.ip2long.php):
Changelog
Version Description
5.2.10 Prior to this version, ip2long() would sometimes return a valid number even if passed an value which was not an (IPv4) Internet Protocol dotted address.
So, as you are using a newer version than 5.2.9 and it doesn't work anymore.
Update: But it will work maybe on some systems as the inet_addr C function on which relies the ip2long function is not a part of the C standard: every system may have its own implementation of it. Some of these implementations have fallback modes for invalid IP addresses. You shouldn't rely on this as the most unix derivatives don't have such a fallback.
Upvotes: 1
Reputation: 8118
If you're using ip2long
for IP validation, I suggest using filter_var($ip, FILTER_VALIDATE_IP
instead.
Upvotes: 1