Chris Lupi
Chris Lupi

Reputation: 23

Python Convert an IP address encoded in Base64 to a Decimal IP address

I am very new to programming and Python so please bear with me. I have a string that is Base64 and I want to convert it to decimal. The string can come in to the script as any value, for example zAvIAQ. This value represents an IP address which is 204.11.200.1 when converted to decimal. What I want to do is convert the Base64 string to decimal and assign it to a variable so that I can use it elsewhere in the script.

I have tried to use the base64.decode function, but that just gives me a very strange text output. I have tried to use the Decimal() function but that gives me an error. After searching for several days now I haven't found a way to do this, at least not one that I can understand. Any help that you can provide would be appreciated.

Upvotes: 2

Views: 4234

Answers (3)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798606

First decode the base64-encoded string using decode('base64') and then decode the resulting number into an IP quartet by using socket.inet_ntoa. Like this:

>>> socket.inet_ntoa('zAvIAQ=='.decode('base64'))
'204.11.200.1'

Upvotes: 6

ThomasH
ThomasH

Reputation: 23516

I usually use base64.b64decode(). With that you get:

In [18]: base64.b64decode('zAvIAQ==')
Out[18]: '\xcc\x0b\xc8\x01'

That is probably the weird output you were referring to. The point is that you get a byte string back, with each byte representing a value between 0 and 255. Those values might not be printable, hence the \x representation.

But as you know that these are the buckets of an IPv4 address, you go through them converting them to decimals, e.g. with the generator expression:

[ord(c) for c in ...]

and you get the more familiar representation 204, 11, 200, 1.

Upvotes: 1

Mark Ransom
Mark Ransom

Reputation: 308138

>>> address=[ord(c) for c in base64.b64decode('zAvIAQ==')]
>>> address
[204, 11, 200, 1]

Upvotes: 3

Related Questions