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?
>>> 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 generate IPs like 0.0.0.0
, 255.255.255.255
.
If you just want a string:
import random ip = ".".join(map(str, (random.randint(0, 255) for _ in range(4))))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With