donglangtun1850 2013-04-12 01:18
浏览 243
已采纳

使用PHP和CIDR计算IP范围

I've seen various questions and answers around this site and I'm still having difficulty wrapping my head around this problem (could be because I've got a cold). Regardless, I'm trying to come up with a small web app that will create tables of IP addresses for each of our offices.

Like say if I create a new scope for 10.1.10.0/4 it will create an array (which I can then print to a table) of:

 10.1.10.0 network ID
 10.1.10.1 gateway
 10.1.10.2 usable
 10.1.10.3 broadcast

(not that it would insert the descriptions automatically but that's what we'd be doing).

I'm pretty sure I'm going to be using ip2long/long2ip to store the addresses as integers but still.

  • 写回答

4条回答 默认 最新

  • doufei5315 2013-04-16 20:29
    关注

    As you've already noted, all IPv4 addresses can be converted to numbers using ip2long(), and converted back using long2ip(). The critical extra bit I'm not sure you've noticed is that sequential IPs correspond with sequential numbers, so you can manipulate these numbers!

    Given a CIDR prefix (e.g, $prefix = 30 for your range), you can calculate the number of IPs in that range using a bit shift operator:

    $ip_count = 1 << (32 - $prefix);
    

    And then loop through all the IPs in that range using:

    $start = ip2long($start_ip);
    for ($i = 0; $i < $ip_count; $i++) {
        $ip = long2ip($start + $i);
        // do stuff with $ip...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用