note 16260 modified in function.ip2long by danbrown
| From: | danbrown@php.net | Date: | Fri, 05 Dec 2008 13:47:24 +0000 |
| Subject: | note 16260 modified in function.ip2long by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-147711@lists.php.net to get a copy of this message | ||
Here's a function I whipped up today to deduce some important network information given a
hostname (or its IP address) and its subnet mask:
<?php
function find_net($host,$mask) {
### Function to determine network characteristics
### $host = IP address or hostname of target host (string)
### $mask = Subnet mask of host in dotted decimal (string)
### returns array with
### "cidr" => host and mask in CIDR notation
### "network" => network address
### "broadcast" => broadcast address
###
### Example: find_net("192.168.37.215","255.255.255.224")
### returns:
### "cidr" => 192.168.37.215/27
### "network" => 192.168.37.192
### "broadcast" => 192.168.37.223
###
$bits=strpos(decbin(ip2long($mask)),"0");
$net["cidr"]=gethostbyname($host)."/".$bits;
$net["network"]=long2ip(bindec(decbin(ip2long(gethostbyname($host))) &
decbin(ip2long($mask))));
$binhost=str_pad(decbin(ip2long(gethostbyname($host))),32,"0",STR_PAD_LEFT);
$binmask=str_pad(decbin(ip2long($mask)),32,"0",STR_PAD_LEFT);
for ($i=0; $i<32; $i++) {
if (substr($binhost,$i,1)=="1" || substr($binmask,$i,1)=="0") {
$broadcast.="1";
} else {
$broadcast.="0";
}
}
$net["broadcast"]=long2ip(bindec($broadcast));
return $net;
}
?>
--was--
Here's a function I whipped up today to deduce some important network information given a
hostname (or its IP address) and its subnet mask:
function find_net($host,$mask) {
### Function to determine network characteristics
### $host = IP address or hostname of target host (string)
### $mask = Subnet mask of host in dotted decimal (string)
### returns array with
### "cidr" => host and mask in CIDR notation
### "network" => network address
### "broadcast" => broadcast address
###
### Example: find_net("192.168.37.215","255.255.255.224")
### returns:
### "cidr" => 192.168.37.215/27
### "network" => 192.168.37.192
### "broadcast" => 192.168.37.223
###
$bits=strpos(decbin(ip2long($mask)),"0");
$net["cidr"]=gethostbyname($host)."/".$bits;
$net["network"]=long2ip(bindec(decbin(ip2long(gethostbyname($host))) &
decbin(ip2long($mask))));
$binhost=str_pad(decbin(ip2long(gethostbyname($host))),32,"0",STR_PAD_LEFT);
$binmask=str_pad(decbin(ip2long($mask)),32,"0",STR_PAD_LEFT);
for ($i=0; $i<32; $i++) {
if (substr($binhost,$i,1)=="1" || substr($binmask,$i,1)=="0") {
$broadcast.="1";
} else {
$broadcast.="0";
}
}
$net["broadcast"]=long2ip(bindec($broadcast));
return $net;
}
http://php.net/manual/en/function.ip2long.php