2010-09-08 07:28:20

Calculating network subnetting with Python

I created this program last year just as an exercise to make sure that I understood the mathmatical processes behind IP subnetting, and could create a network calculator based off that information.

The code below isn't meant to be pretty ... If I spent a little time on it, I could modularize, simplify, and comment the heck out of it, but this code is a byproduct of the network subnetting task that I set for myself, not the end result.

The program will randomly generate an IP and subnet, then generate a quiz for the following questions:

  • Class
  • Increment
  • Netmask
  • IP Address in binary
  • Netmask in binary
  • Network IP
  • Broadcast IP
  • Number of subnets
  • Number of hosts
#!/bin/env python
#################################################################
# Who: James Conner
# When: Feb 24, 2009
# What: pysub
# Version: 0.0.1
# Why: Test subnetting for Cisco exams
#################################################################
# Updates:
# 0.0.1:James Conner:Feb 24, 2009
#   Initial creation
# 0.0.2:James Conner:Feb 27, 2009
#   Added network and broadcast IPs
#################################################################
# Notes:
# Need error and exception controls
#################################################################

#################################################################
# Modules
#################################################################
import optparse
import sys, os
import string
import random
import datetime


#################################################################
# Global Variables
#################################################################
stamp = datetime.datetime.now()


#################################################################
# Classes
#################################################################


#################################################################
# Functions
#################################################################
def int2bin(n, count=8):
  return "".join([str((n >> y) & 1) for y in range(count-1, -1, -1)])

def gen_IP():
  oct1=random.randrange(0,223)
  oct2=random.randrange(0,255)
  oct3=random.randrange(0,255)
  oct4=random.randrange(0,255)
  while oct1 == 127:
    oct1=random.randrange(0,223)
  ipaddr=str(oct1)+"."+str(oct2)+"."+str(oct3)+"."+str(oct4)
  ipaddr_list=[oct1,oct2,oct3,oct4]
  ipaddr_list_binary=[int2bin(ipaddr_list[0]), int2bin(ipaddr_list[1]), int2bin(ipaddr_list[2]), int2bin(ipaddr_list[3])]
  ipaddr_binary=ipaddr_list_binary[0]+"." +ipaddr_list_binary[1]+"." +ipaddr_list_binary[2]+"." +ipaddr_list_binary[3]

  if oct1 <= 126:
    netclass="A"
  elif oct1 <= 191:
    netclass="B"
  elif oct1 <= 223:
    netclass="C"
  else:
    print("Determining netclass failed")

  randmask=str(256-(2**random.randrange(0,8)))

  if netclass == "C":
    while randmask=="255":
      randmask=str(256-(2**random.randrange(0,8)))
    netmask_temp=[255,255,255,randmask]
  elif netclass == "B":
    a=random.randrange(0,1)
    if a == 0:
      while randmask=="255":
        randmask=str(256-(2**random.randrange(0,8)))
      netmask_temp=[255,255,255,randmask]
    elif a == 1:
      netmask_temp=[255,255,randmask,0]
    else:
      print("netclass_temp B is out of bounds")
  elif netclass == "A":
    a=random.randrange(0,2)
    if a == 0:
      while randmask=="255":
        randmask=str(256-(2**random.randrange(0,8)))
      netmask_temp=[255,255,255,randmask]
    elif a == 1:
      netmask_temp=[255,255,randmask,0]
    elif a == 2:
      netmask_temp=[255,randmask,0,0]
    else:
      print("netclass_temp A is out of bounds")
  else:
    print("No netclass corresponding")
  netmask_list=[netmask_temp[0],netmask_temp[1],netmask_temp[2],netmask_temp[3]]
  netmask=str(netmask_list[0])+"." +str(netmask_list[1])+"." +str(netmask_list[2])+"."+ str(netmask_list[3])
  netmask_list_binary=[int2bin(int(netmask_list[0])), int2bin(int(netmask_list[1])), int2bin(int(netmask_list[2])), int2bin(int(netmask_list[3]))]
  netmask_binary=str(netmask_list_binary[0])+"." +str(netmask_list_binary[1])+"." +str(netmask_list_binary[2])+"." +str(netmask_list_binary[3])
  increment=256-int(randmask)
  netip_list=[int(ipaddr_list[0])& int(netmask_list[0]),int(ipaddr_list[1])& int(netmask_list[1]),int(ipaddr_list[2])& int(netmask_list[2]),int(ipaddr_list[3])& int(netmask_list[3])]
  broadcastip_mask_list=[((int(ipaddr_list[0])| int(netmask_list[0]))-255)*-1,((int(ipaddr_list[1])| int(netmask_list[1]))-255)*-1,((int(ipaddr_list[2])| int(netmask_list[2]))-255)*-1,((int(ipaddr_list[3])| int(netmask_list[3]))-255)*-1]
  broadcastip_list=[int(ipaddr_list[0])+ int(broadcastip_mask_list[0]), int(ipaddr_list[1])+ int(broadcastip_mask_list[1]), int(ipaddr_list[2])+ int(broadcastip_mask_list[2]), int(ipaddr_list[3])+ int(broadcastip_mask_list[3])]


  broadcastip=str(broadcastip_list[0])+"."+ str(broadcastip_list[1])+"." +str(broadcastip_list[2])+"." +str(broadcastip_list[3])
  netip=str(netip_list[0])+"." +str(netip_list[1])+"." +str(netip_list[2])+"." +str(netip_list[3])


  if netclass == "A":
    subnets=(2**(str(netmask_binary).count("1")-8))
  elif netclass == "B":
    subnets=(2**(str(netmask_binary).count("1")-16))
  elif netclass == "C":
    subnets=(2**(str(netmask_binary).count("1")-24))
  else:
    print("subnets is messed up")

  hosts=(2**(str(netmask_binary).count("0"))-2)

  print("-"*64)
  print("IP: "+str(ipaddr)+"/"+str(str(netmask_binary).count("1")))
  print("-"*64)

  answer_class = raw_input("Class: ")
  if answer_class == netclass:
    print ("Correct!")
  else:
    print ("Wrong! The answer is: "+str(netclass))

  answer_increment = raw_input("Increment: ")
  if str(answer_increment) == str(increment):
    print ("Correct!")
  else:
    print ("Wrong! The answer is: "+str(increment))

  answer_netmask = raw_input("Mask: ")
  if str(answer_netmask) == str(netmask):
    print ("Correct!")
  else:
    print ("Wrong! The answer is: "+str(netmask))

  answer_ipaddr_binary = raw_input("IP Binary: ")
  if str(answer_ipaddr_binary) == str(ipaddr_binary):
    print ("Correct!")
  else:
    print ("Wrong! The answer is: "+str(ipaddr_binary))

  answer_netmask_binary = raw_input("Mask Binary: ")
  if str(answer_netmask_binary) == str(netmask_binary):
    print ("Correct!")
  else:
    print ("Wrong! The answer is: "+str(netmask_binary))

  answer_netip = raw_input("Network IP: ")
  if str(answer_netip) == str(netip):
    print ("Correct!")
  else:
    print ("Wrong! The answer is: "+str(netip))

  answer_broadcastip = raw_input("Broadcast IP: ")
  if str(answer_broadcastip) == str(broadcastip):
    print ("Correct!")
  else:
    print ("Wrong! The answer is: "+str(broadcastip))

  answer_subnets = raw_input("Subnets: ")
  if str(answer_subnets) == str(subnets):
    print ("Correct!")
  else:
    print ("Wrong! The answer is: "+str(subnets))

  answer_hosts = raw_input("Hosts: ")
  if str(answer_hosts) == str(hosts):
    print ("Correct!")
  else:
    print ("Wrong! The answer is: "+str(hosts))



#################################################################
# Option Parser
#################################################################
parser = optparse.OptionParser(version = "0.0.2")
parser.set_defaults(mode="advanced")
(opts, arg) = parser.parse_args()


#################################################################
# Program Execution
#################################################################
if __name__ == '__main__':
    gen_IP()

Tags:   python     |    Perm Link:   Calculating network subnetting with Python



James Conner