Start and end IP addresses for a network segment For example: Network segment (192168.1.5/24), whose subnet mask is divided according to 24: 11111111.11111111.11111111.00000000 (255.255.255.0) Description: The IP address is 32bits,24 in the division of the network segment is indicated in front of 24 1, followed by 8 0. The algorithm for starting the IP address is: The binary of the 192.168.1.5 and the subnet mask binary are "with" the Operation out. The algorithm for ending an IP address is: The binary of the subnet mask is first reversed, and then the "or" operation is performed with the binary of the 192.168.1.5 The actual application, that is, the network address and broadcast address, network address +1 is the first host address, 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 (' 192 ', ' 168 ', ' 1 ', ' 5 ');//Set IP address, which can be obtained from the form, only for demonstration
- $mask = ' 24 '; Set Mask
- $bSub = Mask2bin ($mask); To convert a subnet mask into binary
- $mask = Array ();
- $mask [] = substr ($bSub, "0", 8); Divide the subnet mask 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 '
|
The first one is 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 ".";
- }
- ?> Copy Code
|
-
|