3

I have an ip address in this format

b'\xd4\xfbuW'

I know that this is an actual IP address, but I don't know how I can print it as a normal (like 192.168.1.1) address and also store it in my memory as a string. How can I decode this hex bytearray?

2 Answers 2

4

You don't need the socket module.

If you have Python 3.6 or above you can use:

print('.'.join(f'{c}' for c in b'\xd4\xfbuW'))

otherwise

print('.'.join(str(c) for c in b'\xd4\xfbuW'))
Sign up to request clarification or add additional context in comments.

Comments

2

You can use the socket module functions, for instance:

import socket

ip_string = '192.168.1.1'
print(socket.inet_aton(ip_string))
print(socket.inet_ntoa(socket.inet_aton(ip_string)))
print(socket.inet_pton(socket.AF_INET, '192.168.1.1'))
print(socket.inet_ntop(
    socket.AF_INET, socket.inet_pton(socket.AF_INET, '192.168.1.1')))

packed_ip = b'\xd4\xfbuW'
print(socket.inet_ntoa(b'\xd4\xfbuW'))

Output

b'\xc0\xa8\x01\x01'
192.168.1.1
b'\xc0\xa8\x01\x01'
192.168.1.1
212.251.117.87

As you can see, 192.168.1.1 would correspond to \xC0\xA8\x01\x01 and b'\xd4\xfbuW' would be 212.251.117.87

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.