Skip to content

Instantly share code, notes, and snippets.

@JuniorPolegato
Created June 15, 2016 12:45
Show Gist options
  • Save JuniorPolegato/eb4ecc975d99d26005b61b9142e0e291 to your computer and use it in GitHub Desktop.
Save JuniorPolegato/eb4ecc975d99d26005b61b9142e0e291 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def num2mask(num):
return str(32-(len(bin(int(num)))-3)) # str(bin(2**32-int(num)).count('1'))
def ip2num(ip):
if '/' in ip:
ip = ip.split('/')[0]
return sum(int(n) << b * 8 for b, n in enumerate(ip.split('.')[::-1]))
def emendar(lan1, lan2):
net1, mask1 = lan1.split('/')
net2, mask2 = lan2.split('/')
# Precisam ter a mesma máscara
if mask1 != mask2:
return None
# Forma numérica
num1 = ip2num(net1)
num2 = ip2num(net2)
mask = 32 - int(mask1)
# num1 precisa ser o início de faixa de (mask1 - 1) = (mask + 1)
if num1 != (num1 & (0xFFFFFFFF << (mask + 1)) & 0xFFFFFFFF):
return None
# num2 precisa ser num1 mais 1 bit da faixa toda de mask
if num1 + (1 << mask) == num2:
return net1 + '/' + str(int(mask1) - 1)
# wget 'ftp://ftp.lacnic.net/pub/stats/lacnic/delegated-lacnic-latest'\
# -O lacnic.txt
lacnic = [l.split('|') for l in open('lacnic.txt').read().strip().split('\n')]
lans = [c[3] + '/' + num2mask(c[4])
for c in lacnic if c[1] == 'BR' and c[2] == 'ipv4']
lans.sort(key=ip2num)
llans = len(lans)
# Reduzir lans que pondem ser emendadas diminuindo do valor da máscara lan/mask
teve_emenda = True
emendas = 0
while teve_emenda:
i = 1
teve_emenda = False
emendas += 1
while i < len(lans):
# print "Verificando:", lans[i - 1], lans[i]
e = emendar(lans[i - 1], lans[i])
if e:
print 'Emendado:', emendas, lans[i - 1], lans[i], e
del lans[i]
lans[i - 1] = e
teve_emenda = True
else:
i += 1
print ' '.join(lans)
print '-' * 100
print 'Diminuiu de', llans, 'para', len(lans)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment