-3

我想做类似的事情:Matching an IP to a CIDR mask in PHP 5?

除了,我想在 MySQL 表中存储一个不允许的 IP/掩码列表并检查匹配。

就像链接中的示例一样,“10.2.0.0/16”之类的内容将是表中的一行,然后我想检查当前用户的 IP 地址 ($_SERVER['REMOTE_ADDR']) 并检查它是否匹配与否。

非常感谢 :)

4

2 回答 2

3

表格上的一些选项 - 您可以将 IP 存储为人类可读的字符串(4 个点分字节)或 cidr_match 使用的本机长数字。假设我们坚持人类可读(cidr_match从链接页面重用)

function testIP($ip=$_SERVER['REMOTE_ADDR']) {
    //Returns TRUE - valid, FALSE - denied

    /* Get the data from the database and return it in rows
     * this could be real-time retrieved, or pulled into an array
     * first
     * assumes: deny_ranges(ip VARCHAR(45) not null,mask INT not null default 0)
     * eg: $denyips= get "SELECT ip,mask FROM deny_ranges" from database
     */

    foreach($denyips as $row) {
        if ($row["mask"]==0) {
            //No need to use overhead of CIDR_MATCH
            //Exact match - reject
            if ($row["ip"]==$ip) return false;
        } elseif (cidr_match($ip,$row["ip"]."/".$row["mask"])==true) {
            //In denied range - reject
            return false;
        }
    }
    //Got through all rejected ranges+ips - it's good
    return true;
}

(您可以cird_match在其他帖子中找到)

于 2010-08-30T17:22:17.790 回答
0

php.net 文档ip2long()在评论中有一个很好的工作代码示例:http ://www.php.net/manual/en/function.ip2long.php#86793

于 2009-10-30T03:54:31.823 回答