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
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'
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加