Reputation: 783
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
Upvotes: 2
Views: 396
Reputation: 26900
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'
Upvotes: 2
Reputation: 3711
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
Upvotes: 1