Skip to content

Instantly share code, notes, and snippets.

@huzemin
Created January 19, 2020 07:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save huzemin/f50632480d337052e9bd7fe04158116e to your computer and use it in GitHub Desktop.
Save huzemin/f50632480d337052e9bd7fe04158116e to your computer and use it in GitHub Desktop.
判断IP是否属于某个网段
<?php
function ipInNetwork($ip, $network) {
if(!filter_var($ip, FILTER_VALIDATE_IP)) {
throw new \Exception($ip . '不是有效IP地址');
}
if(!preg_match('/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\/\d+/', $network)) {
throw new \Exception($network . '不是有效网段设置,如:192.168.0.1/24');
}
$s = explode('/', $network);
$ipBin = decbin(ip2long($s[0]));
if(32 < $s[1]) {
throw new \Exception('网段掩码位必须为0-32');
}
$maskBin = str_repeat('1', $s[1]).str_repeat('0', 32 - $s[1]);
$ipNet = ($ipBin & $maskBin);
$ipBin = decbin(ip2long($ip));
$cipNet = ($ipBin & $maskBin);
return $ipNet == $cipNet;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment