Home > Backend Development > PHP Tutorial > How to calculate IP address mask in php

How to calculate IP address mask in php

*文
Release: 2023-03-18 21:50:02
Original
2977 people have browsed it

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";
Copy after login

Result:

IP地址 : 192.168.1.12
子网掩码: 255.255.255.0
IP段开始: 192.168.1.0
IP段结束: 192.168.1.255
Copy after login

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"));
Copy after login

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!

Related labels:
source:php.cn
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