Find the start and end IP addresses of a CIDR block 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.
- Function 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. This example is used only for demonstration.
- $ Mask = '24'; // sets the mask.
- $ BSub = mask2bin ($ mask); // Convert the subnet mask to binary
- $ Mask = array ();
- $ Mask [] = substr ($ bSub, "0", 8); // divide the subnet mask into eight parts.
- $ 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 ".";
- }
- ?>
|
|