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\",
You also have Python's ipaddress module available to you, useful more broadly for creating, manipulating and operating on IPv4 and IPv6 addresses and networks:
import ipaddress
import random
MAX_IPV4 = ipaddress.IPv4Address._ALL_ONES # 2 ** 32 - 1
MAX_IPV6 = ipaddress.IPv6Address._ALL_ONES # 2 ** 128 - 1
def random_ipv4():
return ipaddress.IPv4Address._string_from_ip_int(
random.randint(0, MAX_IPV4)
)
def random_ipv6():
return ipaddress.IPv6Address._string_from_ip_int(
random.randint(0, MAX_IPV6)
)
Examples:
>>> random.seed(444)
>>> random_ipv4()
'79.19.184.109'
>>> random_ipv4()
'3.99.136.189'
>>> random_ipv4()
'124.4.25.53'
>>> random_ipv6()
'4fb7:270d:8ba9:c1ed:7124:317:e6be:81f2'
>>> random_ipv6()
'fe02:b348:9465:dc65:6998:6627:1300:29c9'
>>> random_ipv6()
'74a:dd88:1ff2:bfe3:1f3:81ad:debd:db88'