This article describes how to obtain the starting and ending IP addresses of a network segment in php. it involves php string operations and hexadecimal conversion techniques, for more information, see the following example. Share it with you for your reference. The details are as follows:
For example, for a network segment (192168.1.5/24), its subnet mask is divided:
11111111.11111111.11111111.00000000 (255.255.255.0)
Note: If the IP address is 32 bits, 24 indicates that there are 24 first 1 and 8 are later 0 in the network segment division.
The algorithm for starting an IP address is: the binary of 192.168.1.5 and the binary of the subnet mask.
The algorithm for ending an IP address is: the subnet mask is first reversed, and then "or" is performed with the 192.168.1.5 binary.
In practice, the network address and broadcast address are obtained as follows. network address + 1 is the first host address, and broadcast address-1 is the last host address.
<? Phpfunction mask2bin ($ n) {$ n = intval ($ n); if ($ n <0 | $ n> 32) die ('error submask '); return str_repeat ("1", $ n ). str_repeat ("0", 32-$ n);} function revBin ($ s) {$ p = array ('0', '1', '2 '); $ r = array ('2', '0', '1'); return str_replace ($ p, $ r, $ s);} function startIp ($ str, $ bSub) {$ bIp = decbin ($ str); $ bIp = str_pad ($ bIp, 8, "0", STR_PAD_LEFT ); $ sIp = bindec ($ bIp & $ bSub); return $ sIp;} function endIp ($ str, $ bSub) {$ bIp = decbin ($ str ); $ bIp = str_pad ($ bIp, 8, "0", STR_PAD_LEFT); $ eIp = bindec ($ bIp | revBin ($ bSub); return $ eIp ;} $ ip = array ('123', '123', '1', '5'); // Set the ip address, which can be obtained from the form, here we will only demonstrate $ mask = '24'; // Set The mask $ bSub = mask2bin ($ mask); // Convert the subnet mask to binary $ mask = array (); $ mask [] = substr ($ bSub, "0", 8); // divide the subnet mask into segments every 8 bits $ mask [] = substr ($ bSub, "8", 8); $ mask [] = substr ($ bSub, "16", 8); $ mask [] = substr ($ bSub, "24 ", 8); echo'
| Mask: |
'; For ($ I = 0; $ I <4; $ I ++) {echo bindec ($ mask [$ I]); if ($ I! = 3) echo ".";} echo' |
| Network address: |
'; For ($ I = 0; $ I <4; $ I ++) {echo startIp ($ ip [$ I], $ mask [$ I]); if ($ I! = 3) echo ".";} echo' |
| First available: |
'; For ($ I = 0; $ I <3; $ I ++) {echo startIp ($ ip [$ I], $ mask [$ I]); echo ". ";}$ ip_4 = startIp ($ ip [3], $ mask [3]); echo ++ $ ip_4; echo' |
| Last available: |
'; For ($ I = 0; $ I <3; $ I ++) {echo endIp ($ ip [$ I], $ mask [$ I]); echo ". ";}$ ip_4 = endIp ($ ip [3], $ mask [3]); echo -- $ ip_4; echo' |
| Broadcast address: |
'; For ($ I = 0; $ I <4; $ I ++) {echo endIp ($ ip [$ I], $ mask [$ I]); if ($ I! = 3) echo "." ;}?> I hope this article will help you with php programming. |