Search code examples
pythonip-addressbroadcast

Calculate broadcast by IP and mask


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

screenshot


Solution

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