7

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

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Why do you do `int(bin(int(octet)), 2)`? That's the same as `int(octet)`. – Barmar Nov 15 '17 at 21:21
  • 1
    Don't reinvent the wheel. Use the lib! https://docs.python.org/3/library/ipaddress.html#ipaddress.IPv4Network.broadcast_address – Klaus D. Nov 15 '17 at 22:26

2 Answers2

10

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
gammazero
  • 773
  • 6
  • 13
3

-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)]
Florian Weimer
  • 32,022
  • 3
  • 48
  • 92