免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2003 | 回复: 0
打印 上一主题 下一主题

PHP对IP地址和子网掩码的处理方法 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-06-24 23:27 |只看该作者 |倒序浏览
ip2long IP地址转换成整型。
long2ip 整型数据转换成IP。
子网掩码转换成掩码长度方式:
$slash_notation = strlen(preg_replace("/0/", "", decbin(ip2long($subnet_mask))));
$bits=strpos(decbin(ip2long($mask)),"0");
子网掩码位长转换成子网掩码形式:
$mask = 0xffffffff $mask = pow(2,32)-pow(2,(32-$mask));
判断两个地址是否在一个子网内:
function matchCIDR($addr, $cidr) {
   list($ip, $mask) = explode('/', $cidr);
   return (ip2long($addr) >> (32 - $mask) == ip2long($ip) >> (32 - mask));
}
?>
一个IPv4的类:
//--------------
// IPv4 class
class ipv4
{
  var $address;
  var $netbits;
   //--------------
  // Create new class
  function ipv4($address,$netbits)
  {
    $this->address = $address;
    $this->netbits = $netbits;
  }
   //--------------
  // Return the IP address
  function address() { return ($this->address); }
   //--------------
  // Return the netbits
  function netbits() { return ($this->netbits); }
   //--------------
  // Return the netmask
  function netmask()
  {
    return (long2ip(ip2long("255.255.255.255")
           32-$this->netbits)));
  }
   //--------------
  // Return the network that the address sits in
  function network()
  {
    return (long2ip((ip2long($this->address))
           & (ip2long($this->netmask()))));
  }
   //--------------
  // Return the broadcast that the address sits in
  function broadcast()
  {
    return (long2ip(ip2long($this->network())
           | (~(ip2long($this->netmask())))));
  }
   //--------------
  // Return the inverse mask of the netmask
  function inverse()
  {
    return (long2ip(~(ip2long("255.255.255.255")
           32-$this->netbits))));
  }
}
  $ip = new ipv4("192.168.2.1",24);
  print "Address: $ip->address()\n";
  print "Netbits: $ip->netbits()\n";
  print "Netmask: $ip->netmask()\n";
  print "Inverse: $ip->inverse()\n";
  print "Network: $ip->network()\n";
  print "Broadcast: $ip->broadcast()\n";
?>
这个做法比较有创意:
For those poor little people using PHP 3, here's an ip2long:
if (!function_exists("ip2long")) {
function ip2long($ip) {
  $ex = explode(".", $ip);
  if (count($ex)!=4) return -1;
  list($a, $b, $c, $d) = $ex;
  $a = $a*16777216;
  $b = $b*65536;
  $c = $c*256;
  return $a+$b+$c+$d;
}
}
?>
#!/usr/local/bin/php
" . long2ip($bc - 1)  . "\n";
?>
Produces the output:
IP Address:         172.14.1.57
Subnet Mask:        255.255.255.0
Network Address:    172.14.1.0
Broadcast Address:  172.14.1.255
Number of Hosts:    254
Host Range:         172.14.1.1 -> 172.14.1.254
               
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/2389/showart_1010530.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP