Monday, January 07, 2008

Translate Decimal / IP dotted quad

Here are simple functions to translate decimal/ip dotted quad in python.
Usage:
>dot2dec("64.233.189.99")
1089060195L
>dec2dot(1089060195L)
'64.233.189.99'
>
import types
def dot2dec(ipForm, useHex = False):
if type(ipForm) == types.StringType:
ipf = ipForm.split(".")
elif type(ipForm) in (types.ListType, types.TupleType):
ipf = ipForm
elif type(ipForm) in (types.LongType, types.IntType):
return None
return reduce(lambda a,b: long(a)*256 + long(b), ipf)

def dec2dot(numbericIP):
if type(numbericIP) == types.StringType and not numbericIP.isdigit() :
return None
numIP = long(numbericIP)
return "%d.%d.%d.%d" % ((numIP>>24)&0xFF, (numIP>>16)&0xFF, (numIP>>8)&0xFF, numIP&0xFF)




FYI:
python google group

No comments: