note 94290 added to function.ip2long
| From: | david dot schueler at tel-billig dot de | Date: | Tue, 27 Oct 2009 14:41:16 +0000 |
| Subject: | note 94290 added to function.ip2long | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-162154@lists.php.net to get a copy of this message | ||
To get the network adress out of the broadcast adress and netmask just to an AND on it:
<?php
// simple example
$bcast = ip2long("192.168.178.255");
$smask = ip2long("255.255.255.0");
$nmask = $bcast & $smask;
echo long2ip($nmask); // Will give 192.168.178.0
?>
With this example you are able to check if a given host is in your own local net or not (on linux):
<?php
/**
* Check if a client IP is in our Server subnet
*
* @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));
}
?>
----
Server IP: 217.160.72.57
Probable Submitter: 84.184.125.16
----
Manual Page -- http://www.php.net/manual/en/function.ip2long.php
Edit -- https://master.php.net/note/edit/94290
Del: integrated -- https://master.php.net/note/delete/94290/integrated
Del: useless -- https://master.php.net/note/delete/94290/useless
Del: bad code -- https://master.php.net/note/delete/94290/bad+code
Del: spam -- https://master.php.net/note/delete/94290/spam
Del: non-english -- https://master.php.net/note/delete/94290/non-english
Del: in docs -- https://master.php.net/note/delete/94290/in+docs
Del: other reasons-- https://master.php.net/note/delete/94290
Reject -- https://master.php.net/note/reject/94290
Search -- https://master.php.net/manage/user-notes.php