Guest User

Untitled

a guest
Jul 19th, 2018
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.20 KB | None | 0 0
  1. import socket,struct
  2.  
  3. def makeMask(n):
  4. "return a mask of n bits as a long integer"
  5. return (2L<<n-1) - 1
  6.  
  7. def dottedQuadToNum(ip):
  8. "convert decimal dotted quad string to long integer"
  9. return struct.unpack('L',socket.inet_aton(ip))[0]
  10.  
  11. def networkMask(ip,bits):
  12. "Convert a network address to a long integer"
  13. return dottedQuadToNum(ip) & makeMask(bits)
  14.  
  15. def addressInNetwork(ip,net):
  16. "Is an address in a network"
  17. return ip & net == net
  18.  
  19. address = dottedQuadToNum("192.168.1.1")
  20. networka = networkMask("10.0.0.0",24)
  21. networkb = networkMask("192.168.0.0",24)
  22. print (address,networka,networkb)
  23. print addressInNetwork(address,networka)
  24. print addressInNetwork(address,networkb)
  25.  
  26. False
  27. True
  28.  
  29. import socket,struct
  30.  
  31. def addressInNetwork(ip,net):
  32. "Is an address in a network"
  33. ipaddr = struct.unpack('L',socket.inet_aton(ip))[0]
  34. netaddr,bits = net.split('/')
  35. netmask = struct.unpack('L',socket.inet_aton(netaddr))[0] & ((2L<<int(bits)-1) - 1)
  36. return ipaddr & netmask == netmask
  37.  
  38. from netaddr import CIDR, IP
  39.  
  40. if IP("192.168.0.1") in CIDR("192.168.0.0/24"):
  41. print "Yay!"
  42.  
  43. from netaddr import IPNetwork, IPAddress
  44. if IPAddress("192.168.0.1") in IPNetwork("192.168.0.0/24"):
  45. print "Yay!"
  46.  
  47. >>> import ipaddress
  48. >>> ipaddress.ip_address('192.168.0.1') in ipaddress.ip_network('192.168.0.0/24')
  49. True
  50.  
  51. n = ipaddress.ip_network('192.0.0.0/16')
  52. netw = int(n.network_address)
  53. mask = int(n.netmask)
  54.  
  55. a = int(ipaddress.ip_address('192.0.43.10'))
  56. a = struct.unpack('!I', socket.inet_pton(socket.AF_INET, '192.0.43.10'))[0]
  57. a = struct.unpack('!I', socket.inet_aton('192.0.43.10'))[0] # IPv4 only
  58.  
  59. in_network = (a & mask) == netw
  60.  
  61. def addressInNetwork(ip, net):
  62. import socket,struct
  63. ipaddr = int(''.join([ '%02x' % int(x) for x in ip.split('.') ]), 16)
  64. netstr, bits = net.split('/')
  65. netaddr = int(''.join([ '%02x' % int(x) for x in netstr.split('.') ]), 16)
  66. mask = (0xffffffff << (32 - int(bits))) & 0xffffffff
  67. return (ipaddr & mask) == (netaddr & mask)
  68.  
  69. >>> print addressInNetwork('10.9.8.7', '10.9.1.0/16')
  70. True
  71. >>> print addressInNetwork('10.9.8.7', '10.9.1.0/24')
  72. False
  73.  
  74. def addressInNetwork(ip,net):
  75. "Is an address in a network"
  76. ipaddr = struct.unpack('>L',socket.inet_aton(ip))[0]
  77. netaddr,bits = net.split('/')
  78. netmask = struct.unpack('>L',socket.inet_aton(netaddr))[0]
  79. ipaddr_masked = ipaddr & (4294967295<<(32-int(bits))) # Logical AND of IP address and mask will equal the network address if it matches
  80. if netmask == netmask & (4294967295<<(32-int(bits))): # Validate network address is valid for mask
  81. return ipaddr_masked == netmask
  82. else:
  83. print "***WARNING*** Network",netaddr,"not valid with mask /"+bits
  84. return ipaddr_masked == netmask
  85.  
  86. def ipToInt(ip):
  87. o = map(int, ip.split('.'))
  88. res = (16777216 * o[0]) + (65536 * o[1]) + (256 * o[2]) + o[3]
  89. return res
  90.  
  91. def isIpInSubnet(ip, ipNetwork, maskLength):
  92. ipInt = ipToInt(ip)#my test ip, in int form
  93.  
  94. maskLengthFromRight = 32 - maskLength
  95.  
  96. ipNetworkInt = ipToInt(ipNetwork) #convert the ip network into integer form
  97. binString = "{0:b}".format(ipNetworkInt) #convert that into into binary (string format)
  98.  
  99. chopAmount = 0 #find out how much of that int I need to cut off
  100. for i in range(maskLengthFromRight):
  101. if i < len(binString):
  102. chopAmount += int(binString[len(binString)-1-i]) * 2**i
  103.  
  104. minVal = ipNetworkInt-chopAmount
  105. maxVal = minVal+2**maskLengthFromRight -1
  106.  
  107. return minVal <= ipInt and ipInt <= maxVal
  108.  
  109. >>> print isIpInSubnet('66.151.97.0', '66.151.97.192',24)
  110. True
  111. >>> print isIpInSubnet('66.151.97.193', '66.151.97.192',29)
  112. True
  113. >>> print isIpInSubnet('66.151.96.0', '66.151.97.192',24)
  114. False
  115. >>> print isIpInSubnet('66.151.97.0', '66.151.97.192',29)
  116.  
  117. import socket,struct
  118.  
  119. def addressInNetwork(ip, net_n_bits):
  120. ipaddr = struct.unpack('!L', socket.inet_aton(ip))[0]
  121. net, bits = net_n_bits.split('/')
  122. netaddr = struct.unpack('!L', socket.inet_aton(net))[0]
  123. netmask = (0xFFFFFFFF >> int(bits)) ^ 0xFFFFFFFF
  124. return ipaddr & netmask == netaddr
  125.  
  126. def bb(i):
  127. def s = '{:032b}'.format(i)
  128. def return s[0:8]+"."+s[8:16]+"."+s[16:24]+"."+s[24:32]
  129.  
  130. def addressInNetwork3(ip,net):
  131. '''This function allows you to check if on IP belogs to a Network'''
  132. ipaddr = struct.unpack('=L',socket.inet_aton(ip))[0]
  133. netaddr,bits = net.split('/')
  134. netmask = struct.unpack('=L',socket.inet_aton(calcDottedNetmask(int(bits))))[0]
  135. network = struct.unpack('=L',socket.inet_aton(netaddr))[0] & netmask
  136. return (ipaddr & netmask) == (network & netmask)
  137.  
  138. def calcDottedNetmask(mask):
  139. bits = 0
  140. for i in xrange(32-mask,32):
  141. bits |= (1 << i)
  142. return "%d.%d.%d.%d" % ((bits & 0xff000000) >> 24, (bits & 0xff0000) >> 16, (bits & 0xff00) >> 8 , (bits & 0xff))
  143.  
  144. import ipaddr
  145.  
  146. a = ipaddr.IPAddress('192.168.0.1')
  147. n = ipaddr.IPNetwork('192.168.0.0/24')
  148.  
  149. #This will return True
  150. n.Contains(a)
  151.  
  152. >>> from netaddr import all_matching_cidrs
  153. >>> all_matching_cidrs("212.11.70.34", ["192.168.0.0/24","212.11.64.0/19"] )
  154. [IPNetwork('212.11.64.0/19')]
  155.  
  156. >>> help(all_matching_cidrs)
  157.  
  158. Help on function all_matching_cidrs in module netaddr.ip:
  159.  
  160. all_matching_cidrs(ip, cidrs)
  161. Matches an IP address or subnet against a given sequence of IP addresses and subnets.
  162.  
  163. @param ip: a single IP address or subnet.
  164.  
  165. @param cidrs: a sequence of IP addresses and/or subnets.
  166.  
  167. @return: all matching IPAddress and/or IPNetwork objects from the provided
  168. sequence, an empty list if there was no match.
  169.  
  170. netmask
  171.  
  172. def addressInNetwork(ip, net_n_bits):
  173. ipaddr = struct.unpack('<L', socket.inet_aton(ip))[0]
  174. net, bits = net_n_bits.split('/')
  175. netaddr = struct.unpack('<L', socket.inet_aton(net))[0]
  176. netmask = ((1L << int(bits)) - 1)
  177. return ipaddr & netmask == netaddr & netmask
  178.  
  179. #!/usr/bin/env python
  180.  
  181. class Node:
  182. def __init__(self):
  183. self.left_child = None
  184. self.right_child = None
  185. self.data = "-"
  186.  
  187. def setData(self, data): self.data = data
  188. def setLeft(self, pointer): self.left_child = pointer
  189. def setRight(self, pointer): self.right_child = pointer
  190. def getData(self): return self.data
  191. def getLeft(self): return self.left_child
  192. def getRight(self): return self.right_child
  193.  
  194. def __str__(self):
  195. return "LC: %s RC: %s data: %s" % (self.left_child, self.right_child, self.data)
  196.  
  197.  
  198. class LPMTrie:
  199.  
  200. def __init__(self):
  201. self.nodes = [Node()]
  202. self.curr_node_ind = 0
  203.  
  204. def addPrefix(self, prefix):
  205. self.curr_node_ind = 0
  206. prefix_bits = ''.join([bin(int(x)+256)[3:] for x in prefix.split('/')[0].split('.')])
  207. prefix_length = int(prefix.split('/')[1])
  208. for i in xrange(0, prefix_length):
  209. if (prefix_bits[i] == '1'):
  210. if (self.nodes[self.curr_node_ind].getRight()):
  211. self.curr_node_ind = self.nodes[self.curr_node_ind].getRight()
  212. else:
  213. tmp = Node()
  214. self.nodes[self.curr_node_ind].setRight(len(self.nodes))
  215. tmp.setData(self.nodes[self.curr_node_ind].getData());
  216. self.curr_node_ind = len(self.nodes)
  217. self.nodes.append(tmp)
  218. else:
  219. if (self.nodes[self.curr_node_ind].getLeft()):
  220. self.curr_node_ind = self.nodes[self.curr_node_ind].getLeft()
  221. else:
  222. tmp = Node()
  223. self.nodes[self.curr_node_ind].setLeft(len(self.nodes))
  224. tmp.setData(self.nodes[self.curr_node_ind].getData());
  225. self.curr_node_ind = len(self.nodes)
  226. self.nodes.append(tmp)
  227.  
  228. if i == prefix_length - 1 :
  229. self.nodes[self.curr_node_ind].setData(prefix)
  230.  
  231. def searchPrefix(self, ip):
  232. self.curr_node_ind = 0
  233. ip_bits = ''.join([bin(int(x)+256)[3:] for x in ip.split('.')])
  234. for i in xrange(0, 32):
  235. if (ip_bits[i] == '1'):
  236. if (self.nodes[self.curr_node_ind].getRight()):
  237. self.curr_node_ind = self.nodes[self.curr_node_ind].getRight()
  238. else:
  239. return self.nodes[self.curr_node_ind].getData()
  240. else:
  241. if (self.nodes[self.curr_node_ind].getLeft()):
  242. self.curr_node_ind = self.nodes[self.curr_node_ind].getLeft()
  243. else:
  244. return self.nodes[self.curr_node_ind].getData()
  245.  
  246. return None
  247.  
  248. def triePrint(self):
  249. n = 1
  250. for i in self.nodes:
  251. print n, ':'
  252. print i
  253. n += 1
  254.  
  255. n=LPMTrie()
  256. n.addPrefix('10.25.63.0/24')
  257. n.addPrefix('10.25.63.0/16')
  258. n.addPrefix('100.25.63.2/8')
  259. n.addPrefix('100.25.0.3/16')
  260. print n.searchPrefix('10.25.63.152')
  261. print n.searchPrefix('100.25.63.200')
  262. #10.25.63.0/24
  263. #100.25.0.3/16
  264.  
  265. #!/usr/bin/python
  266. >>> calcDottedNetmask(21)
  267. >>> '255.255.248.0'
  268.  
  269. #!/usr/bin/python
  270. >>> addressInNetwork('188.104.8.64','172.16.0.0/12')
  271. >>>True which is completely WRONG!!
  272.  
  273. #!/usr/bin/python
  274. import socket,struct
  275. def addressInNetwork(ip,net):
  276. '''This function allows you to check if on IP belogs to a Network'''
  277. ipaddr = struct.unpack('=L',socket.inet_aton(ip))[0]
  278. netaddr,bits = net.split('/')
  279. netmask = struct.unpack('=L',socket.inet_aton(calcDottedNetmask(bits)))[0]
  280. network = struct.unpack('=L',socket.inet_aton(netaddr))[0] & netmask
  281. return (ipaddr & netmask) == (network & netmask)
  282.  
  283. def calcDottedNetmask(mask):
  284. bits = 0
  285. for i in xrange(32-int(mask),32):
  286. bits |= (1 > 24, (bits & 0xff0000) >> 16, (bits & 0xff00) >> 8 , (bits & 0xff))
  287.  
  288. #!/usr/bin/python
  289. >>> addressInNetwork('188.104.8.64','172.16.0.0/12')
  290. False
  291.  
  292. struct.unpack('!L', ... )
  293.  
  294. import socket
  295. import struct
  296.  
  297. def makeMask(n):
  298. "return a mask of n bits as a long integer"
  299. return (2L<<n-1) - 1
  300.  
  301. def dottedQuadToNum(ip):
  302. "convert decimal dotted quad string to long integer"
  303. return struct.unpack('L',socket.inet_aton(ip))[0]
  304.  
  305. def addressInNetwork(ip,net,netmask):
  306. "Is an address in a network"
  307. print "IP "+str(ip) + " NET "+str(net) + " MASK "+str(netmask)+" AND "+str(ip & netmask)
  308. return ip & netmask == net
  309.  
  310. def humannetcheck(ip,net):
  311. address=dottedQuadToNum(ip)
  312. netaddr=dottedQuadToNum(net.split("/")[0])
  313. netmask=makeMask(long(net.split("/")[1]))
  314. return addressInNetwork(address,netaddr,netmask)
  315.  
  316.  
  317. print humannetcheck("192.168.0.1","192.168.0.0/24");
  318. print humannetcheck("192.169.0.1","192.168.0.0/24");
  319.  
  320. import SubnetTree
  321. t = SubnetTree.SubnetTree()
  322. t.insert("10.0.1.3/32")
  323. print("10.0.1.3" in t)
  324.  
  325. import socket,struct
  326. def addressInNetwork(ip,net):
  327. "Is an address in a network"
  328. ipaddr = struct.unpack('!L',socket.inet_aton(ip))[0]
  329. netaddr,bits = net.split('/')
  330. netaddr = struct.unpack('!L',socket.inet_aton(netaddr))[0]
  331. netmask = ((1<<(32-int(bits))) - 1)^0xffffffff
  332. return ipaddr & netmask == netaddr & netmask
  333. print addressInNetwork('10.10.10.110','10.10.10.128/25')
  334. print addressInNetwork('10.10.10.110','10.10.10.0/25')
  335. print addressInNetwork('10.10.10.110','10.20.10.128/25')
  336.  
  337. def ip_to_u32(ip):
  338. return int(''.join('%02x' % int(d) for d in ip.split('.')), 16)
  339.  
  340. SNS_SOURCES = [
  341. # US-EAST-1
  342. '207.171.167.101',
  343. '207.171.167.25',
  344. '207.171.167.26',
  345. '207.171.172.6',
  346. '54.239.98.0/24',
  347. '54.240.217.16/29',
  348. '54.240.217.8/29',
  349. '54.240.217.64/28',
  350. '54.240.217.80/29',
  351. '72.21.196.64/29',
  352. '72.21.198.64/29',
  353. '72.21.198.72',
  354. '72.21.217.0/24',
  355. ]
  356.  
  357. def build_masks():
  358. masks = [ ]
  359. for cidr in SNS_SOURCES:
  360. if '/' in cidr:
  361. netstr, bits = cidr.split('/')
  362. mask = (0xffffffff << (32 - int(bits))) & 0xffffffff
  363. net = ip_to_u32(netstr) & mask
  364. else:
  365. mask = 0xffffffff
  366. net = ip_to_u32(cidr)
  367. masks.append((mask, net))
  368. return masks
  369.  
  370. ip = ip_to_u32(ipstr)
  371. for mask, net in cached_masks:
  372. if ip & mask == net:
  373. # matched!
  374. break
  375. else:
  376. raise BadClientIP(ipstr)
  377.  
  378. class iptools:
  379. @staticmethod
  380. def dottedQuadToNum(ip):
  381. "convert decimal dotted quad string to long integer"
  382. return struct.unpack('>L', socket.inet_aton(ip))[0]
  383.  
  384. @staticmethod
  385. def numToDottedQuad(n):
  386. "convert long int to dotted quad string"
  387. return socket.inet_ntoa(struct.pack('>L', n))
  388.  
  389. @staticmethod
  390. def makeNetmask(mask):
  391. bits = 0
  392. for i in xrange(32-int(mask), 32):
  393. bits |= (1 << i)
  394. return bits
  395.  
  396. @staticmethod
  397. def ipToNetAndHost(ip, maskbits):
  398. "returns tuple (network, host) dotted-quad addresses given"
  399. " IP and mask size"
  400. # (by Greg Jorgensen)
  401. n = iptools.dottedQuadToNum(ip)
  402. m = iptools.makeMask(maskbits)
  403. net = n & m
  404. host = n - mask
  405. return iptools.numToDottedQuad(net), iptools.numToDottedQuad(host)
  406.  
  407. # -*- coding: utf-8 -*-
  408. import socket
  409.  
  410.  
  411. class SubnetTest(object):
  412. def __init__(self, network):
  413. self.network, self.netmask = network.split('/')
  414. self._network_int = int(socket.inet_aton(self.network).encode('hex'), 16)
  415. self._mask = ((1L << int(self.netmask)) - 1) << (32 - int(self.netmask))
  416. self._net_prefix = self._network_int & self._mask
  417.  
  418. def match(self, ip):
  419. '''
  420. 判断传入的 IP 是不是本 Network 内的 IP
  421. '''
  422. ip_int = int(socket.inet_aton(ip).encode('hex'), 16)
  423. return (ip_int & self._mask) == self._net_prefix
  424.  
  425. st = SubnetTest('100.98.21.0/24')
  426. print st.match('100.98.23.32')
  427.  
  428. def ip_matches_network(self, network, ip):
  429. """
  430. '{:08b}'.format(254): Converts 254 in a string of its binary representation
  431.  
  432. ip_bits[:net_mask] == net_ip_bits[:net_mask]: compare the ip bit streams
  433.  
  434. :param network: string like '192.168.33.0/24'
  435. :param ip: string like '192.168.33.1'
  436. :return: if ip matches network
  437. """
  438. net_ip, net_mask = network.split('/')
  439. net_mask = int(net_mask)
  440. ip_bits = ''.join('{:08b}'.format(int(x)) for x in ip.split('.'))
  441. net_ip_bits = ''.join('{:08b}'.format(int(x)) for x in net_ip.split('.'))
  442. # example: net_mask=24 -> compare strings at position 0 to 23
  443. return ip_bits[:net_mask] == net_ip_bits[:net_mask]
  444.  
  445. def IP2Int(ip):
  446. o = map(int, ip.split('.'))
  447. res = (16777216 * o[0]) + (65536 * o[1]) + (256 * o[2]) + o[3]
  448. return res
  449.  
  450.  
  451. def addressInNetwork(ip, net_n_bits):
  452. ipaddr = IP2Int(ip)
  453. net, bits = net_n_bits.split('/')
  454. netaddr = IP2Int(net)
  455. bits_num = int(bits)
  456. netmask = ((1L << bits_num) - 1) << (32 - bits_num)
  457. return ipaddr & netmask == netaddr & netmask
Add Comment
Please, Sign In to add comment