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\"
,
If you're looking for speed, try out Mimesis
from mimesis import Internet
random_ip = Internet().ip_v4()
If you're looking to generate a random IP adress with a valid CIDR, try out Faker
from faker import Faker
random_valid_ip = Faker().ipv4()
For more details on why Faker takes longer, see this issue.
An alternative way to generate a random string in the form of an IP address is:
>>> ip = '{}.{}.{}.{}'.format(*__import__('random').sample(range(0,255),4))
>>> ip
'45.162.105.102'
If you just want a string:
import random
ip = ".".join(map(str, (random.randint(0, 255)
for _ in range(4))))