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

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

青灯夜游
青灯夜游forward
2020-07-17 15:57:302835browse

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 )

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 )

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

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

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

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!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete