Home > Article > Backend Development > PHP determines whether an IP4 belongs to a certain IP segment
Many times, we need to create an IP blacklist or IP whitelist to restrict visitors. A very common one is to restrict all IPs in the same IP segment. Allow or restrict, then we need to know whether the visitor IP belongs to the IP range. This article only records the method.
In fact, there is another application scenario in this article, that is, the IP addresses stored in the database are usually of varchar type. If the INT type is used to save the IP, it can optimize the database. Of course, here This is only explained for IP4.
To determine whether an IP belongs to a certain IP segment, the idea is to convert the IP into an int type value and then compare it. PHP has built-in functions for exchanging ip and numerical values: ip2long($ip_addr) and long2ip($long).
In ip2long($ip_addr), if $ip_addr is not a valid IP address, false will be returned. If it is a valid IP address, it will be converted to a signed long type. Sometimes the IP address is converted The signed long length may be exceeded, which results in a negative number.
The long type is 4 bytes, its signed range is: 2147483647 ~ -2147483648, the unsigned range is: 4294967295 ~ 0
And the largest IP4 address is: 255.255. 255.255, the corresponding value is: 4294967295, so it can be converted into an unsigned value. The IP corresponding to the value 2147483647 is: 127.255.255.255,
long2ip(2147483647), so there will be no negative numbers for IP addresses in the range of 0.0.0.0 to 127.255.255.255, but in the range of 128.0.0.0 to 255.255.255.255 There will be negative numbers within.
The following code gives a complete and correct example of determining whether a specified IP belongs to a certain IP segment.
$start_ip = "42.236.184.1"; $end_ip = "42.236.184.255"; $ip = "42.236.184.128"; check_ip($ip,$start_ip,$end_ip); function check_ip($ip,$start_ip,$end_ip) { $ip = get_ip2long($ip); $start_ip = get_ip2long($start_ip); $end_ip = get_ip2long($end_ip); if($ip >= $start_ip && $ip <= $end_ip) { return true; } return false; } // decbin() 十进制转二进制 // bindec() 二进制转十进制。函数将一个二进制数转换成 integer。可转换的最大的数为 31 位 1 或者说十进制的 2147483647。PHP 4.1.0 开始,该函数可以处理大数值,这种情况下,它会返回 float 类型。 function get_ip2long($ip) { return bindec(decbin(ip2long($ip))); //方法二:return sprintf('%u',ip2long($ip)); //%u:不包含正负号的十进制数 }
For more PHP related knowledge, please visit PHP Chinese website!
The above is the detailed content of PHP determines whether an IP4 belongs to a certain IP segment. For more information, please follow other related articles on the PHP Chinese website!