Match IPv4 address given IP range/mask?

后端 未结 6 697
一生所求
一生所求 2020-12-28 12:06

Either with PHP or a RegExp (or both), how do I match a range of IP addresses?

Sample Incoming IPs

10.210.12.12
10.253.12.12
10.210.12.254
10.210.1         


        
6条回答
  •  长发绾君心
    2020-12-28 12:26

    I've improved on the above example (I have a netmask with /29 so it doesn't work).

    function check_netmask($mask, $ip) {
        @list($net, $bits) = explode('/', $mask);
        $bits = isset($bits) ? $bits : 32;
        $bitmask = -pow(2, 32-$bits) & 0x00000000FFFFFFFF;
        $netmask = ip2long($net) & $bitmask;
        $ip_bits = ip2long($ip)  & $bitmask;
        return (($netmask ^ $ip_bits) == 0);
    }
    

    If you want to see it in action, add this:

    print("IP Bits: " . str_pad(decbin(ip2long($ip)), 32, '0', STR_PAD_LEFT));
    print "\n";
    print("Bitmask: " . str_pad(decbin($bitmask), 32, '0', STR_PAD_LEFT));
    print "\n";
    print("Netmask: " . str_pad(decbin($netmask), 32, '0', STR_PAD_LEFT));
    print "\n";
    print("Match:   " . str_pad(decbin($netmask ^ $ip_bits), 32, '0', STR_PAD_LEFT));
    print "\n";
    

    Run it with something like this:

    print var_dump(check_netmask($argv[1], $argv[2]));
    

提交回复
热议问题