Created
January 19, 2020 07:15
-
-
Save huzemin/f50632480d337052e9bd7fe04158116e to your computer and use it in GitHub Desktop.
判断IP是否属于某个网段
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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