此脚本可以根据输入的主机数量 规划子网段的划分,适用于交流学习。
示例:

python版本建议3.8及以上。
如果需求是给定子网数量,均匀划分子网的话,主页有beta版本,欢迎查看!
import heapq
class Node:
def __init__(self, key=None, freq=0):
self.key = key
self.freq = freq
self.left = None
self.right = None
# 优先队列(堆)需要支持小于操作
def __lt__(self, other):
return self.freq < other.freq
def build_huffman_tree(frequency):
heap = []
for key, freq in frequency.items():
heapq.heappush(heap, Node(key, freq))
while len(heap) > 1:
node1 = heapq.heappop(heap)
node2 = heapq.heappop(heap)
merged = Node(freq=node1.freq + node2.freq)
merged.left = node1
merged.right = node2
heapq.heappush(heap, merged)
return heap[0] if heap else None
def generate_codes(root, current_code='', codes={}):
if root is None:
return
if root.key is not None:
codes[root.key] = current_code
return
generate_codes(root.left, current_code + '0', codes)
generate_codes(root.right, current_code + '1', codes)
def huffman_encoding(frequency):
root = build_huffman_tree(frequency)
codes = {}
generate_codes(root, '', codes)
return codes
# 将十进制IP转化为二进制
def get_BinaryIP(IP):
tmp = IP.split('.')
Blist = []
Blist.append("{:08b}".format(int(tmp[0])))
Blist.append("{:08b}".format(int(tmp[1])))
Blist.append("{:08b}".format(int(tmp[2])))
Blist.append("{:08b}".format(int(tmp[3].split('/')[0])))
Blist.append(int(tmp[3].split('/')[1]))
BIPtmp = ''
for i in Blist:
BIPtmp += str(i)
BIP = BIPtmp[:32:] + '/' + BIPtmp[32::]
return BIP
# 将二进制IP转化为十进制
def get_DecimalIP(IP):
tmp = IP.split('/')
Dlist = []
Dlist.append(int(tmp[0][:8:], 2))
Dlist.append(int(tmp[0][8:16:], 2))
Dlist.append(int(tmp[0][16:24:], 2))
Dlist.append(int(tmp[0][24:32:], 2))
DIPtmp = ''
for i in Dlist:
DIPtmp += str(i)
DIPtmp += '.'
DIP = DIPtmp[:-1:] + '/' + str(tmp[1])
return DIP
# 输出大于num的 2的n次方序列 的最小项
def limit_2_index(num):
for i in range(0, 32):
if num < 2**i - 2: # 减2是因为要考虑网络号(全0)和广播号(全1)
return 2**i
def main():
# 输入可分配网段
ANS = '192.168.36.0/24'
inputANS = input("输入待分配网段(默认 192.168.10.0/24):")
if inputANS:
ANS = inputANS
tail = int(ANS.split('/')[1]) # 网络号位数
capacity = 2**(32 - tail) # 计算 提供的网段 所能容纳的 主机数量
dic0, dic = {}, {} # dic0存放原始输入信息,dic存放经过limit_2_index函数处理过的输入信息
# 输入子网段主机数列表
int_input = [10,20,30,40]
print("请输入各网段的主机数,每个网段以空格间隔")
inputSubnet = input("(默认 10 20 30 40 ): ")
if inputSubnet:
int_input = list(map(int,inputSubnet.split(' ')))
for i in range(len(int_input)):
dic0[i] = int_input[i]
dic[i] = limit_2_index(int_input[i])
if sum(dic.values()) > capacity:
print("主机数量太多了!")
exit()
sorted_huffman_codes = sorted(huffman_encoding(dic).items(), key=lambda x: x[0])
for key, value in sorted_huffman_codes:
btail = tail + len(value) # 子网的网络号位数
for i in range(32 - btail): # 将子网的非网络位补齐
get_BinaryIP(ANS)
value += '0'
BIP = get_BinaryIP(ANS)[:tail] + str(value) + '/' + str(btail)
print(dic0[key], ':', get_DecimalIP(BIP))
# print(BIP)
if __name__ == "__main__":
main()
如有问题欢迎私信。
转载请标明原出处,谢谢!
553



被折叠的 条评论
为什么被折叠?



