Wednesday, March 23, 2011

[Level 2] get broadcast by Python

I wrote a python script to get broadcast by giving ip and netmask.
And I use "lambda" and "map" function to shorten my code,
so it's also a good sample for you to study map function.
More information please refer here.
The sample code is as the following:
#!/bin/env python
def getBroadcast(self, ip=None, netmask=None):
    if not ip or not netmask: return None
    ip = ip.split('.')
    netmask = netmask.split('.')
    for n in range(0,4):
        if netmask[n] == '0': break
    bc = (map(lambda a, b: str(int(a, 10)&int(b,10)), ip[0:n]+['255']*(4-n), netmask[0:n]+['255']*(4-n)))

    if n > 1: bc[n-1] = str(int(bc[n-1]) + (255 - int(netmask[n-1])))
    return '.'.join(bc)

print getBroadcast('','')
Wish this helps.
Stanley Huang