Calculate broadcast by IP and mask [duplicate]

大兔子大兔子 提交于 2020-01-02 06:22:13

问题


i'm trying to calculate broadcast address by logic OR and NOT with specified ip and mask, but the func return me smth strange. Why?

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


回答1:


-64 and 192 are actually the same value as 8-bit bytes. You just need to mask the bytes with 0xff to get numbers in the more standard 0…255 range instead of the -128…127 range you have now. Something like this:

broadcast = [(ioctet | ~moctet) & 0xff for ioctet, moctet in zip(ip, mask)]



回答2:


Instead of optimizing the Python code, use the ipaddress module to do the work. 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)

OUTPUT:

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


来源:https://stackoverflow.com/questions/47316777/calculate-broadcast-by-ip-and-mask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!