2

I am running the below function in python (3x) to generate a random IP Address

def get_ip_address(self):
            x = ".".join(map(str, (random.randint(0, 255)
                                   for _ in range(4))))
            return x

However I need to convert the IP address generated into a hex value, I dont need to do anything complicated and am happy to either convert x post creation or do it in the create Ip address function. I need to be able to easily see what the IP address is I am creating and converting as this is part of a test Suite and at the other end the Hex IP Address is converted back. I also need it in the format 0xb15150ca

2 Answers 2

2

You're complicating things. Just take the IP address as an int and convert it into hex:

# Generate a random 
>>> hex(random.randint(0,(1<<32)-1))
'0x85c90851'
>>> hex(random.randint(0,(1<<32)-1))
'0xfb4f592d'

If you always wish for it to be exactly 8 hex digits, and strip the 0x up front, you may as well format it straight like this:

>>> "{:0X}".format(random.randint(0,(1<<32)-1))
'4CC27A5E'

If you wish to know the IP, use the ipaddress module like so:

import ipaddress
>>> ip = random.randint(0,(1<<32)-1)
>>> ipaddress.ip_address(ip)
IPv4Address('238.53.246.162')
>>> "{:0X}".format(ip)
'EE35F6A2'
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks this works great for encoding, but I need to know what the IP address is before its encoded (should have mentioned that in the question sorry).
@RichardC Edited.
1

You can extend you function as follows:

def get_ip_address():

    x = ".".join(map(str, (random.randint(0, 255)
                           for _ in range(4))))

    # Split you created decimal IP in single numbers
    ip_split_dec = str(x).split('.')

    # Convert to hex
    ip_split_hex = [int(t) for t in ip_split_dec]

    # Construct hex IP adress
    # ip_hex = '.'.join([hex(X)[2:] for X in ip_split_hex]) # Format hh.hh.hh.hh
    ip_hex = '0x' + ''.join([hex(X)[2:] for X in ip_split_hex]) # Format 0xhhhhhhhh

    return ip_hex

which will give you

>>> address = get_ip_address()
>>> 0xa535f08b

You can also combine this with the construction of your decimal IP to spare some code lines

Btw: As long as your function is no method of a class, theres is no need for the self in your function definition

3 Comments

The function is part of a larger class hence the self. I need the IP address to be in the format 0xb15150ca thanks.
In that case you can use the edited code from my answer or adapt the code of @bharel answer below
Going for the other option, this works but the other option is a simpler overall solution.

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.