Getting list IPs from CIDR notation in PHP

前端 未结 13 1336
慢半拍i
慢半拍i 2020-12-08 05:38

Is there a way (or function/class) to get the list of IP addresses from a CIDR notation?

For example, I have 73.35.143.32/27 CIDR and want to get the list of all IP\

13条回答
  •  [愿得一人]
    2020-12-08 06:07

    Well, it's a bitmask - 73.35.143.32/27 means that 27 bits are the network mask, and the rest is available for assigning to the nodes in the network:

    73.35.143.32
    

    in binary is this (dots shown for legibility):

    01001001.00100011.10001111.00100000
    

    The netmask is 27 bits:

    11111111.11111111.11111111.11100000
    

    So you can just AND them together and get this:

    01001001.00100011.10001111.001 00000
     network prefix (27 bits)     | node address (5 bits)
    

    From here, you can just enumerate all the combinations in the node address (00000 is 0, 11111 is 31, so a simple loop is enough), and you'll have all the available hosts.

    Converting this pseudocode to PHP is left as an exercise to the reader ;)

    Oh, and the obligatory deprecation warning: IPv4 is now full, consider also IPv6.

提交回复
热议问题