ip_classifier.py for ipv32
Written simple program to find the class for an ip address of 32bit version
#!/usr/bin/python import sys, getopt def __help(): sys.stderr.write('\n Usage: \n ip_classifier.py -h \n ip_classifier.py --help \n ip_classifier.py -i 128.12.14.23 \n ip_classifier.py --ipv4=128.12.14.23 \n ') sys.exit() def __input_validator(check): if len(check) <> 0: check = list(check) c = 0; n = 0 for v in check: if v in ['.','1','2','3','4','5','6','7','8','9','0']: n += 1 test = True if v is '.': c += 1 else: test = False break if test and c < 4 and n > 6: return check else: sys.stderr.write('**** Enter correct ip address **** \n') __help() def __validator(ip): if ip in range(0,256): return True else: sys.stderr.write('**** Enter correct ip address **** \n') __help() def __class_finder(ip, class_ip, bin_ip): i='' dict = {'0' : 'A', '10' : 'B', '110' : 'C', '1110' : 'D', '1111' :'E', 'A' : 1, 'B' : 2, 'C' : 3, 'D' : 0, 'E' : 0} if class_ip[:1] in dict: i = class_ip[:1] if class_ip[:2] in dict: i = class_ip[:2] if class_ip[:3] in dict: i = class_ip[:3] if class_ip in dict: i = class_ip i = dict.get(i) sub = dict.get(i) subnet ='' for v in range(1,5): if v <= sub: subnet += '255.' else: subnet +='0.' subnet = subnet[:len(subnet)-1] print ip + ' is Class '+ i +'\n The subnet is '+subnet print ' The network bits are', bin_ip[:sub*8] print ' The host bits are', bin_ip[sub*8:] sys.exit() def __ip_classifier(ip): # Empty List ip_value = list() # Intialize the list ip_value = []*4 t='' for i in ip: if i <> '.': t += i.strip() else: try: if __validator(int(t)): ip_value.append( int(t)) t ='' except (RuntimeError, TypeError, NameError) as e: pass if __validator(int(t)): ip_value.append( int(t)) # converting ipv32 into binary value bin_ip ='' for v in ip_value: bin_ip += str(bin(v))[2:].zfill(8) sys.stdout.write('Binary value of' + ip +' is '+ bin_ip+'\n') __class_finder(ip, bin_ip[:4], bin_ip) def main(argv): try: opts, args = getopt.getopt(argv,"h:i:",['--help',"ipv4="]) except getopt.GetoptError: __help() if len(opts) == 0: __help() for opt, arg in opts: if opt in ['-h', '--help']: __help() elif opt in ("-i", "--ipv4"): ip = arg if __input_validator(ip): __ip_classifier(ip) if __name__ == "__main__": main(sys.argv[1:])
Comments
Post a Comment