我已经为我工作的公司创建了一个网站。
我想限制对预先设置了子网掩码的用户的访问。用PHP可以做到这一点吗?IP地址已知。
发布于 2012-11-17 01:33:27
你问问题的方式?不是的。您无法从服务器端确定客户端的子网掩码。
但是,您可以在服务器端定义自己的网络和掩码,以匹配客户端IP,以确定是否授予访问权限。您应该首先使用read up on how subnetting works,然后使用ip2long()函数和bitwise operations授予对特定网段的访问权限。
不过老实说,大多数时候,当你想通过IP地址限制访问时,你会想要在网络/防火墙级别上这样做,而不是在应用程序中。
发布于 2012-11-17 01:12:17
这很简单:给定IP地址的“子网”掩码是255.255.255.255。
子网掩码与子网一起定义ip地址范围。
因此,要从ip地址收集子网掩码,您需要子网。
我上面的回答有点讽刺,假设子网和ip地址是相同的。这在技术上是不可能的,因为所有4x255位都用于子网,并且没有更多的位可用于任何ip地址。
发布于 2012-11-17 01:19:39
我相信这可能会实现您正在尝试实现的目标:
请参阅http://php.net/manual/en/function.ip2long.php
<?php
/**
* Check if a client IP is in our Server subnet
*
* @author david dot schueler at tel-billig dot de
* @param string $client_ip
* @param string $server_ip
* @return boolean
*/
function clientInSameSubnet($client_ip=false,$server_ip=false) {
if (!$client_ip)
$client_ip = $_SERVER['REMOTE_ADDR'];
if (!$server_ip)
$server_ip = $_SERVER['SERVER_ADDR'];
// Extract broadcast and netmask from ifconfig
if (!($p = popen("ifconfig","r"))) return false;
$out = "";
while(!feof($p))
$out .= fread($p,1024);
fclose($p);
// This is because the php.net comment function does not
// allow long lines.
$match = "/^.*".$server_ip;
$match .= ".*Bcast:(\d{1,3}\.\d{1,3}i\.\d{1,3}\.\d{1,3}).*";
$match .= "Mask:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/im";
if (!preg_match($match,$out,$regs))
return false;
$bcast = ip2long($regs[1]);
$smask = ip2long($regs[2]);
$ipadr = ip2long($client_ip);
$nmask = $bcast & $smask;
return (($ipadr & $smask) == ($nmask & $smask));
}
?>https://stackoverflow.com/questions/13420798
复制相似问题