Calculate broadcast by IP and mask

Viewed 8648

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

2 Answers

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

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