Get broadcast adrdess and network address from an ip and mask

Viewed 26

My task is to get the broadcast address and network address, but I will have to use the subnetMask value and ip given by the user. I can't includes import or import so I could I change the last elements and add points and it should not be complicated because I am a beginner. Here is right I am:

adressIP = (input("Enter a IP adress: "))
subnetMask = (input("Enter a subnet mask: "))

valueIntSubnetMask = subnetMask[1:]
convertedBinaryValue = ""
for d in adressIP.split("."):
    b = bin(int(d))[2:].zfill(8)
    convertedBinaryValue = convertedBinaryValue + b + "."
    convertedBinaryValue = convertedBinaryValue[:-1]

maxIP = valueIntSubnetMask : 32].replace()
minIP = ""
for 
1 Answers

Some example how to implement it, but any implementation should follow the principle to first convert the strings to 32-bit integers, then calculate the network/broadcast address by bitwise-operation, then convert back to strings.

from functools import reduce

ipAddressStr = "192.168.1.244"
subnetMaskStr = "255.255.255.128"

ipAddressBin = reduce(lambda i,s: i<<8 | int(s), ipAddressStr.split("."), 0)
subnetMaskBin = reduce(lambda i,s: i<<8 | int(s), subnetMaskStr.split("."), 0)
networkAddressBin = ipAddressBin & subnetMaskBin
broadcastAddressBin = ipAddressBin | (subnetMaskBin ^ (1<<32)-1)
networkAddressStr = ".".join([str(networkAddressBin>>(8*i)&255) for i in range(3,-1,-1)])
broadcastAddressStr = ".".join([str(broadcastAddressBin>>(8*i)&255) for i in range(3,-1,-1)])

print(networkAddressStr)
print(broadcastAddressStr)

Naturally this can also be written more verbose by defining functions for the conversions:

def ipStrToBin(addrStr):
    addrBin = 0
    for octet in addrStr.split("."):
        addrBin = addrBin << 8 | int(octet)
    return addrBin

def ipBinToStr(addrBin):
    octetsStr = []
    for i in range(4):
        octetsStr.append(str(addrBin>>(8*(3-i))&255))
    return ".".join(octetsStr)

ipAddressStr = "192.168.1.244"
subnetMaskStr = "255.255.255.128"

ipAddressBin = ipStrToBin(ipAddressStr)
subnetMaskBin = ipStrToBin(subnetMaskStr)
networkAddressBin = ipAddressBin & subnetMaskBin
broadcastAddressBin = ipAddressBin | (subnetMaskBin ^ (1<<32)-1)
networkAddressStr = ipBinToStr(networkAddressBin)
broadcastAddressStr = ipBinToStr(broadcastAddressBin)

print(networkAddressStr)
print(broadcastAddressStr)
Related