我试图通过逻辑OR来计算广播地址而不是使用指定的ip和掩码来计算广播地址,但是func让我觉得很奇怪。为什么呢?
IP = '192.168.32.16'
MASK = '255.255.0.0'
def get_ID(ip, mask):
ip = ip.split('.')
mask = mask.split('.')
ip = [int(bin(int(octet)), 2) for octet in ip]
mask = [int(bin(int(octet)), 2) for octet in mask]
subnet = [str(int(bin(ioctet & moctet), 2)) for ioctet, moctet in zip(ip, mask)]
host = [str(int(bin(ioctet & ~moctet), 2)) for ioctet, moctet in zip(ip, mask)]
broadcast = [str(int(bin(ioctet | ~moctet), 2)) for ioctet, moctet in zip(ip, mask)] # a mistake, i guess
print('Subnet: {0}'.format('.'.join(subnet)))
print('Host: {0}'.format('.'.join(host)))
print('Broadcast address: {0}'.format('.'.join(broadcast)))
答案 0 :(得分:4)
使用ipaddress
模块来完成工作,而不是优化Python代码。
https://docs.python.org/3/library/ipaddress.html
import ipaddress
IP = '192.168.32.16'
MASK = '255.255.0.0'
host = ipaddress.IPv4Address(IP)
net = ipaddress.IPv4Network(IP + '/' + MASK, False)
print('IP:', IP)
print('Mask:', MASK)
print('Subnet:', ipaddress.IPv4Address(int(host) & int(net.netmask)))
print('Host:', ipaddress.IPv4Address(int(host) & int(net.hostmask)))
print('Broadcast:', net.broadcast_address)
输出:
IP: 192.168.32.16
Mask: 255.255.0.0
Subnet: 192.168.0.0
Host: 0.0.32.16
Broadcast: 192.168.255.255
答案 1 :(得分:0)
-64和192实际上是与8位字节相同的值。您只需要使用0xff
屏蔽字节,以获得更标准的0 ... 255范围内的数字,而不是现在的-128 ... 127范围。像这样:
broadcast = [(ioctet | ~moctet) & 0xff for ioctet, moctet in zip(ip, mask)]