Krishna Chaitanya
Krishna Chaitanya

Reputation: 181

convert str type dotted decimal (ip address) to hex in python

I have an ip x.x.x.x assigned to a variable returning as str. Need help in converting this str type ip address to hex

Context:

ip = '1.1.1.1'
print type(ip) >>> str

Expected result:
ip = '1.1.1.1'
print ip >>> 0x01010101

Please suggest with out having to import ipaddress module. Because we have different server with python versions 2.6 to 3.3. If this script has to run on any server below 3.2, whomsoever running this script had to pip install ipaddress module. Any help is highly appreciated here.

Upvotes: 1

Views: 1202

Answers (3)

Chiheb Nexus
Chiheb Nexus

Reputation: 9257

You can have your desired output like this example:

def str_to_hex(ip = ''):
    return '0x' + ''.join('{:02x}'.format(int(char)) for char in ip.split('.'))

print(str_to_hex("1.1.1.1"))
print(str_to_hex("213.1.23.1"))
print(str_to_hex("192.168.0.2"))

Output:

0x01010101
0xd5011701
0xc0a80002

Upvotes: 0

shizhz
shizhz

Reputation: 12501

You don't need any extra module to do this, this is a working code snippet:

#!/usr/bin/env python

def ip2hex(ip):
    return "0x" + "".join(map(lambda i: "{:02X}".format(int(i)), ip.split(".")))

if __name__ == '__main__':
    print(ip2hex("1.1.1.1"))
    print(ip2hex("192.168.0.2"))

will give your desired output:

0x01010101

0xC0A80002

Upvotes: 0

Denziloe
Denziloe

Reputation: 8131

"0x" + "".join(format(int(octet), "02x") for octet in ip.split("."))

Upvotes: 1

Related Questions