Monday, March 21, 2011

[Level 2] Implement prefix and netmask transfer with Python.

Sometimes, you want to transfer between netmask and prefix setting.
You can use the following sample script which is written by Python.
#!/bin/env python
def transferPrefix2Netmask(self, prefix):
        netmask = ''
        nLeadingFF = prefix / 8
        netmask += '.'.join(['255']*nLeadingFF)
        if nLeadingFF != 4:
            netmask += '.' + str(256-2**(8-prefix%8))
        nSuffix00 = 3 - nLeadingFF
        if nLeadingFF < 3:
            netmask += '.' + '.'.join(['00']*nSuffix00)
        return netmask
    
    def transferNetmask2Prefix(self, netmask):
        prefix = 0
        left = 0
        for i in netmask.split('.'):
            if i == '255':
                prefix += 8
            else:
                left = int(i)
                break
        if left != 0:
            for n in range(7, 0, -1):
                prefix += 1
                if left - 2 ** n == 0:
                    break
                else:
                    left -= 2 ** n
        return prefix

print transferPrefix2Netmask(16)
print transferPrefix2Netmask(17)
print transferPrefix2Netmask(18)
print transferPrefix2Netmask(22)
print transferPrefix2Netmask(23)
print transferPrefix2Netmask(24)
print transferNetmask2Prefix('255.255.128.0')
print transferNetmask2Prefix('255.255.192.0')
print transferNetmask2Prefix('255.255.252.0')
print transferNetmask2Prefix('255.255.254.0')
print transferNetmask2Prefix('255.255.255.0')
print transferNetmask2Prefix('255.255.255.128')
print transferNetmask2Prefix('255.255.255.192')
print transferNetmask2Prefix('255.255.255.252')
print transferNetmask2Prefix('255.255.255.254')
print transferNetmask2Prefix('255.255.255.255')

Wish this helps. regards, Stanley Huang