2011/07/24

python tips: convert ip-address returned by android api to readable format

In SL4A, wifiGetConnectionInfo contains ip-address of an android device. But it is formatted in integer, difficult to understand. Below script can convert integer formatted ip-addr to human-friendly format 8^)

>>> ip = 67807424
>>> format(ip, 'b')
'100000010101010100011000000'
>>> len(format(ip, 'b'))
27
>>> ipstr = '00000' + format(ip, 'b')
>>> L = []
>>> for i in range(0, 32, 8):
...     L.append(str(int(ipstr[i:i+8], 2)))
... 
>>> L.reverse()
>>> L
['192', '168', '10', '4']
>>> ('.').join(L)
'192.168.10.4'

No comments:

Post a Comment

100