python-通过IP和掩码计算广播
作者:互联网
这个问题已经在这里有了答案: > bit-wise operation unary ~ (invert) 5个
我正在尝试通过逻辑“或”来计算广播地址,而不是使用指定的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)))
解决方法:
-64和192实际上是与8位字节相同的值.您只需要用0xff屏蔽字节即可获得更标准的0…255范围内的数字,而不是现在的-128…127范围内的数字.像这样:
broadcast = [(ioctet | ~moctet) & 0xff for ioctet, moctet in zip(ip, mask)]
标签:ip-address,python,broadcast 来源: https://codeday.me/bug/20191025/1929500.html