Create an IP Address as a hex value

Richard C

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

Bharel

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]

編集
0

コメントを追加

0

関連記事

分類Dev

How to find an address by a hex value in string format?

分類Dev

Using seq and math to manipulate the last octet in an ip address to create a file

分類Dev

How to automatically include client ip address from Request()->ip() in eloquent create method using Laravel 5.2?

分類Dev

IP camera RTSP address

分類Dev

binding ip address to hostname

分類Dev

Shared external IP address

分類Dev

Is this subnetted IP address valid?

分類Dev

PHP Replace binary file at hex address

分類Dev

Calculate CIDR given an IP address

分類Dev

Retrieving the client request ip address

分類Dev

Retrieving the client request ip address

分類Dev

How to set static IP address?

分類Dev

VPN without Static IP address

分類Dev

extracting ip address from a file

分類Dev

How to find ip address in codeigniter?

分類Dev

stop access to website by IP address

分類Dev

assign ip address to domain name

分類Dev

Virtualbox: get host IP address

分類Dev

Regex to match conditional IP address

分類Dev

Can a private IP address change?

分類Dev

VPS IP address for local site

分類Dev

building a hex value from integers

分類Dev

Loading value at address into register

分類Dev

Address of model instead value

分類Dev

PHP get hex value (not the string representation, actually hex)

分類Dev

Reading memory address's in c using user inputted hex values

分類Dev

Browser does not load when ip address is entered directly into the address bar

分類Dev

How to redirect a URL to a custom IP address?

分類Dev

Set SSH Host IP Address on Rackspace for Ansible