Advertisement
Guest User

Untitled

a guest
Jul 7th, 2014
278
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.70 KB | None | 0 0
  1. from socket import inet_aton, inet_ntoa
  2. from struct import unpack, pack
  3.  
  4. # might need to make an IP tools module for now it's all here
  5.  
  6. def ip2long(ip_addr):
  7.     return unpack("!L", inet_aton(ip_addr))[0]
  8.  
  9. def long2ip(ip):
  10.     return inet_ntoa(pack("!L", ip))
  11. ####################################################
  12. # my helper functions
  13.  
  14.     def subNetInfo(network, mask):
  15.         # takes the network address, and return information about the subnet
  16.         # Bcast
  17.         # number of possible subnets
  18.         # number of possible hosts
  19.        
  20.         # want to be able to send the values as either a string or a long
  21.         try:
  22.             intNetwork = ip2long(network)
  23.         except TypeError:
  24.             intNetwork = network
  25.            
  26.         try:
  27.             # take the string mask, and convert it into a bit mask
  28.             temp = ip2long(mask)
  29.             intMask = 0
  30.             while(temp != 0):
  31.                 print bin(temp)[2:].zfill(32)
  32.                 temp = long(temp << 1)
  33.                 intMask += 1
  34.  
  35.         except TypeError:
  36.             intMask = mask
  37.            
  38.         # at this point the network address should be a long and the mask is int
  39.         # here I do two things, shift the bits, and get the reverse mask 1100 would become 0011 the I use the OR to get the bCast
  40.         bCast = intNetwork ^ long(4294967295 >> intMask ) # 4294967295 == 2**32-1 I use this as a constant
  41.         addresses = 2**(32-intMask)
  42.         subnets = 2**(intMask-8)
  43.        
  44.         # lets package this in a dict for easy display
  45.         result = {'bcast': bcast, 'hosts': addresses-2, 'subnets': subnets}
  46.         return result
  47.    
  48. print subNetInfo('10.0.0.0', '255.255.255.0')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement