I am currently learning Python, but I also needed to review subnetting. I have found that one of the best ways to stretch my synapses is to combine learning something new with reviewing something that I learned a while back.
To accomplish my review while still learning a new skill I decided to write a simple program that contains functions for the tasks involved in subnetting. Basically, I aimed to write a mediocre ipcalc. I also decided to write these functions in the way that I would think of them, not necessarily the most efficient way to program them. For example, see this solution vs. mine for converting decimal to binary. My functions include decimal to binary conversion, getting relevant information from a subnet mask, and getting the network id of an IP using a subnet mask. You can get the full code of the following examples here.
The first function, ip_to_binary, is pretty straight forward. It works the same way a person is usually taught to convert IP octets into binary (a.k.a base 2). It generates a list of the powers of two, up to 2^7 as a reference. It then iterates over each octet of the IP address. Within that iteration it iterates over the 2^7 list. If it can subtract the octet from the value in the list, it does so and records a 1 and then subtracts the value of the list from the octet; the program then proceeds with another iteration. If it can’t subtract the value then it just records a 0.
The second function, get_subnet_info, uses the previous function to convert a subnet mask to binary. It then counts the number of masked bits (1) and unmasked bits (o). Finally it uses these counts to find out information such as how many subnets there are, how many hosts are in each subnet, what the CIDR notation is, and what the block size is in decimal for the octet of interest (the one that isn’t 0 or 255). See Sybex CCNA study guide, sixth edition, page 119 for more information on these operations.
The third function just prints the information returned from get_subnet_info in a helpful format.
The last function, get_network_id, takes an IP and subnet mask to get the network id number. This is done by iterating over each octet in the IP and the mask in parallel and performing bitwise AND between the two octets in each iteration. See “The ‘mask’ in subnet mask’ section in IP subnetting made easy to find out how this works.
Learning something new at the same time as reviewing something old creates an energy and agility in my thought process. This combination leads me to make connections between different areas of study. It also makes me learn new information while accessing my memory. Lastly, writing about it clarifies my thoughts and acts as a short term review to wrap it all up.


