This article mainly introduces the method of IP address masking operation in PHP, involving PHP string and network operation related skills. Friends in need can refer to it. I hope to be helpful.
The details are as follows:
ip analysis:
function ip_parse($ip_str) { $mark_len = 32; if (strpos($ip_str, "/") > 0) { list($ip_str, $mark_len) = explode("/", $ip_str); } $ip = ip2long($ip_str); $mark = 0xFFFFFFFF << (32 - $mark_len) & 0xFFFFFFFF; $ip_start = $ip & $mark; $ip_end = $ip | (~$mark) & 0xFFFFFFFF; return array($ip, $mark, $ip_start, $ip_end); } //演示: list($ip, $mark, $ip_start, $ip_end) = ip_parse("192.168.1.12/24"); echo "IP地址 : ", long2ip($ip), "\n"; echo "子网掩码: ", long2ip($mark), "\n"; echo "IP段开始: ", long2ip($ip_start), "\n"; echo "IP段结束: ", long2ip($ip_end), "\n";
Result:
IP地址 : 192.168.1.12 子网掩码: 255.255.255.0 IP段开始: 192.168.1.0 IP段结束: 192.168.1.255
Whether ip is in the ip segment :
function ip_in($ip, $ip_str) { $mark_len = 32; if (strpos($ip_str, "/") > 0) { list($ip_str, $mark_len) = explode("/", $ip_str); } $right_len = 32 - $mark_len; return ip2long($ip) >> $right_len == ip2long($ip_str) >> $right_len; } //演示: var_dump(ip_in("192.168.1.1", "192.168.1.0/24"));
Related recommendations:
php Calculate the time interval between two timestamps
PHP Calculate page execution time
php Calculate the distance between two geographical coordinates
The above is the detailed content of How to calculate IP address mask in php. For more information, please follow other related articles on the PHP Chinese website!