changzhi changzhi - 2 months ago 16
Python Question

Python randomly generated IP address of the string

In Python, what should I do if I want to generate a random string in the form of an IP address?

For example:

"10.0.1.1"
,
"10.0.3.14"
,
"172.23.35.1"
and so on.

Could someone give me some help?

Answer
>>> import random
>>> import socket
>>> import struct
>>> socket.inet_ntoa(struct.pack('>I', random.randint(1, 0xffffffff)))
'197.38.59.143'
>>> socket.inet_ntoa(struct.pack('>I', random.randint(1, 0xffffffff)))
'228.237.175.64'

NOTE This could generarte IPs like 0.0.0.0, 255.255.255.255.