IP Address Subnet Mask calculation

Source: Internet
Author: User
IP Address Subnet mask calculation, return IP segment start and end range, length, mask and other information.
    1. /**
    2. * Mask Calculator
    3. * @author Weaksun <52132522@qq.com>
    4. * @param string $ip IP
    5. * @param Numeric $bits Mask
    6. * @return Array Returns the result set
    7. */
    8. function netmask ($ip, $bits = 24) {
    9. $result = [
    10. ' Start ' = + 0,//First IP
    11. ' End ' = 0,//Last IP
    12. ' Length ' = 0,//number of IPs included
    13. ' Netmask ' = (~pow (2, 32-$bits)) + 1,//subnet mask
    14. ' Networksegment ' = 0,//ip Duan
    15. ' Bcast ' = 0//broadcast address
    16. ];
    17. $result [' length '] = ABS ($result [' netmask '])-2;
    18. $result [' networksegment '] = Ip2long ($IP) & $result [' netmask '];
    19. $result [' start '] = $result [' networksegment '] + 1;
    20. $result [' end '] = $result [' networksegment '] + $result [' length '];
    21. $result [' bcast '] = $result [' End '] + 1;
    22. return $result;
    23. }
Copy Code
    1. List ($ip, $bits) = explode ('/', ' 192.168.1.5/25 ');
    2. $TMPARR = netmask ($ip, $bits);
    3. foreach ($tmpArr as $k = & $v) {
    4. $k! = ' length ' && $v = Long2ip ($v);
    5. }
    6. Echo '
      ' . Var_export ($TMPARR, true). '
      ';
Copy Code
    1. Array (
    2. ' Start ' = ' 192.168.1.1 ',
    3. ' End ' = ' 192.168.1.126 ',
    4. ' Length ' = 126,
    5. ' netmask ' = ' 255.255.255.128 ',
    6. ' Networksegment ' = ' 192.168.1.0 ',
    7. ' Bcast ' = ' 192.168.1.127 ',
    8. )
Copy Code
Subnet mask
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.