The subnet address and broadcast address are not given directly because the condition is given precedence. However, these two parameters require that we use the IP address and subnet mask to derive the subnet address and broadcast address. Ideas are as follows:
1. The subnet address, the IP address and the subnet mask are converted into binary, the two phases, then the subnet address is derived. such as:
192.168.1.1 255.255.255.0 subnet address is 192.168.1.0, converted into binary numbers, the algorithm is as follows.
01100000 01010100 00000001 00000001 (192.168.1.1) & 11111111 11111111 11111111 00000000 (255.255.255.0) = 1100000 1010100 00000001 00000000 is 192.168.1.0. The following is the C code of the algorithm. Using the Inet_aton function, convert the IP address, subnet mask in the form of a string into a network byte order (unin32_t, that is, shaping), and then two numbers to phase, and then use the INET_NTOA function, the network byte-order form of IP address, converted back to The IP address of the dotted decimal type.
Char*getsubnet (CharIp[],Charnetmask[]) { structin_addr addr; structin_addr Mask; structin_addr Subnet; if(Inet_aton (IP, &addr) = =0) {perror ("Inet_aton Error"); returnNULL; } if(Inet_aton (netmask, &mask) = =0) {perror ("Inet_aton Error"); returnNULL; } subnet.s_addr= Addr.s_addr &mask.s_addr; returnInet_ntoa (subnet);}
2. For the broadcast address in the subnet, the calculation is the same as the subnet address, it is necessary to adjust the algorithm. First we reverse the subnet mask, get a new value, and then use that value to do "or" with the IP address. The broadcast address in the subnet is obtained. Then take 192.168.1.1 and 255.255.255.0 as examples, 1111111 1111111 11111111 00000000 ~ = 00000000 00000000 00000000 11111111 00000000 00000000 00000000 11111111 | 01100000 01010100 00000001 00000001 = 01100000 01010100 00000001 11111111 = = 192.168.1.255 The code is as follows:
Char*getbroadip (CharIp[],Charnetmask[]) { structin_addr addr; structin_addr Mask; structin_addr Broadip; if(Inet_aton (IP, &addr) = =0) {perror ("Inet_aton Error"); returnNULL; } if(Inet_aton (netmask, &mask) = =0) {perror ("Inet_aton Error"); returnNULL; } broadip.s_addr= Addr.s_addr | (~mask.s_addr); returnInet_ntoa (BROADIP);}
Derive subnet address and broadcast address based on IP address and mask