简体   繁体   中英

Calculate in which subnet is IP address

I have an IP address and mask (for example IP is 10.128.20.1, mask is 255.255.248.0). How I can calculate, in which subnet range is IP added?

I try implement founded solution, where I list all subnets by IP and mask and next I do test IP address, whether is in subnet. But I try find easier way.

Thanks, I attach a part of solution:

   $ip_addr = "192.168.36.9"; 
   $subnet_mask = "255.255.248.0"; 

   $ip = ip2long($ip_addr); 
   $nm = ip2long($subnet_mask); 
   $nw = ($ip & $nm); 
   $bc = $nw | (~$nm); 

   echo "IP Address:         " . long2ip($ip) . "\n"; 
   echo "Subnet Mask:        " . long2ip($nm) . "\n"; 
   echo "Network Address:    " . long2ip($nw) . "\n"; 
   echo "Broadcast Address:  " . long2ip($bc) . "\n"; 
   echo "Number of Hosts:    " . ($bc - $nw - 1) . "\n"; 
   echo "Host Range:         " . long2ip($nw + 1) . " -> " . long2ip($bc - 1)  . "\n"; 

This work, if I use zero subnet. For no zero subnet this example not work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM