Home > Backend Development > PHP Tutorial > Why does php ip2long have negative numbers? How to deal with it?

Why does php ip2long have negative numbers? How to deal with it?

青灯夜游
Release: 2023-04-09 09:14:01
forward
2863 people have browsed it

Why does php ip2long have negative numbers? How to deal with it?

php provides ip2long and long2ip methods for ip address processing.

1. ip2long - Convert an IPV4 string Internet protocol into a digital format

int ip2long ( string $ip_address )
Copy after login

Parameters: ip_address An address in a standard format.

Return value: Returns the converted number of the IP address or FALSE if ip_address is invalid.

2, long2ip - Convert the number format into an IPV4 string Internet protocol

string long2ip ( string $proper_address )
Copy after login

Parameters: proper_address The correct address of the long integer express.

Return value: Returns the Internet address as a string.

3. How to use

$ip = '10.1.1.1';
$ip_long = ip2long($ip);
echo $ip_long.PHP_EOL; // 167837953
echo long2ip($ip_long); // 10.1.1.1
Copy after login

4. Reasons for negative numbers and how to deal with them

When the IP address is relatively large, Negative numbers will appear in ip2long:

$ip = '192.168.101.100';
$ip_long = ip2long($ip);
echo $ip_long.PHP_EOL; // -1062705820
echo long2ip($ip_long); // 192.168.101.100
Copy after login

Reason explanation:

IPv4 uses unsigned 32-bit addresses, so there are at most 2 to the 32nd power minus 1 (4294967295) addresses. . Write decimal numbers separated by 4 decimal points.

Remember as A.B.C.D, for example: 192.168.100.100.

Each decimal number in the IPv4 address is an unsigned byte, ranging from 0 to 255. Converting the IPv4 address to an unsigned number actually means placing each decimal number in the corresponding 8 bits, forming a 4-byte unsigned integer. 192.168.100.100, 192,168 in the high 8 digits and 100,100 in the low 8 digits.

Solution:

Use %u to format the output as an unsigned integer.

$ip = '192.168.101.100';
$ip_long = sprintf('%u',ip2long($ip));
echo $ip_long.PHP_EOL; // 3232261476 
echo long2ip($ip_long); // 192.168.101.100
Copy after login

Related tutorial recommendations: "PHP Tutorial"

The above is the detailed content of Why does php ip2long have negative numbers? How to deal with it?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template