Prerequisite – Introduction and Classful Addressing, Classless Addressing
Given a valid IPv4 address in the form of string. The task is to determine class of given IPv4 address as well as separate Network and Host ID part from it.
Every host and router on internet has an IP address which encodes its network number and host number, combination of the two is unique. An IP address does not actually refer to a host but refers to a network interface, so if host is on two networks, it must have two IP addresses.
An address mask determines which portion of an IP address represents network number and which part represents host number, e.g., IP address, the mask has four octets. If a given bit of the mask is 1, the corresponding bit of the IP address is in network portion and if given bit of mask is 0, the corresponding bit of IP address is in host portion.
Classless Inter Domain Routing uses slash(/) notation to specify the mask with IPv4 address. The address is given as x.y.z.t/n where x.y.z.t is the IP address and n is the number of 1’s in the default mask.
First address of a network is network address. It is obtained by ANDing the mask with the IP address (Both in binary form). Another method is to set last 32-n bits of the IP address to 0.
Last address of a network is broadcast address. It is obtained by ORing the complement mask with the IP address(Both in binary form). Another method is to set last 32-n bits of the IP address to 1.
Class of an address is identified by the first byte of address. There are currently five classes A, B, C, D and E. The range of first byte of each class is:
Class A: 0 - 127 Class B: 128 - 191 Class C: 192 - 223 Class D: 224 - 239 Class E: 240 - 255
CIDR: 192.168.32.1/24(x.y.z.t/n) IP Address(Binary): 11000000101010000010000000000001 Default Mask(Binary): 11111111111111111111111100000000 Default Mask: 255.255.255.0 32-n=32-24=8 First Address: Set last 8 bits of IP address to 0 = 11000000101010000010000000000000 = 192.168.32.0 Last Address: Set last 8 bits of IP address to 1 = 11000000101010000010000011111111 = 192.168.32.255
CIDR: 18.104.22.168/28(x.y.z.t/n) IP Address(Binary): 11001101000011110010010100100111 Default Mask(Binary): 11111111111111111111111111110000 Default Mask: 255.255.255.240 32-n=32-28=4 First Address: Set last 4 bits of IP address to 0 = 11001101000011110010010100100000 = 22.214.171.124 Last Address: Set last 4 bits of IP address to 1 = 11001101000011110010010100101111 = 126.96.36.199
The following code uses the concepts mentioned above:
IP address CIDR format is:192.168.1.1/24 Class : C Network Address : 192.168.1.0 Broadcast Address : 192.168.1.255