通过IP和掩码计算广播

Calculate broadcast by IP and mask

我正在尝试使用指定的 ip 和掩码通过逻辑 OR 和 NOT 来计算广播地址,但是 func return 我有点奇怪。为什么?

 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)]

不是优化 Python 代码,而是使用 ipaddress 模块来完成这项工作。 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