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)))
The broadcast address is based on your IP address and subnet mask. For example, if your IP address is 10.11. 12.100, and your mask is 255.255. 255.0, then your broadcast will be 10.11.
Another short cut for broadcast address calculation after getting netwotk address is: calculate total no of hosts (in this case it is 2^12 = 4096) Divide it by 256(in this case it is 16) and add the result - 1(in this case 15) in *corresponding octet(in this case second octet i.e. 32+15=47) and make other octet 255.
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With