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?
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'
https://faker.readthedocs.io/en/latest/providers/faker.providers.internet.html
import faker
fake = Factory.create()
ip_addr = fake.ipv4(network=False)
lib has a lot of other useful options to fake data.
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.
from faker import Factory
fake_generator = Factory.create()
print(fake_generator.ipv4())
Be sure to pip install prior to trying to run the above!
pip install Faker
Check out the package documentation: https://faker.readthedocs.io/en/master/index.html
Here is a link directly to the ipv4 method docs
If trying to only generate private IP addresses based off user space (192.168.xxx.xxx, 172.16.xxx.xxx-172.31.255.255, and 10.xxx.xxx.xxx)
This post gives good answers
If you are trying to generate ANYTHING else, which can be considered public, use this (my code is based off the post above):
import random
def randomPublicIPaddress():
'''
oct 1 - cant be 10
oct 2 - if oct1 == 192
cant be 168
if oct1 == 172
cant be 16-31
oct 3 - can be anything
oct 4 - can be anything
'''
oct1 = random.choice([i for i in range(0,255) if i not in [10,127]])
if oct1 == 192:
oct2 = random.choice([i for i in range(0,255) if i not in [168]])
elif oct1 == 172:
oct2 = random.choice([i for i in range(0,255) if i not in range(16,31)])
else:
oct2 = random.randint(0,255)
oct3 = random.randint(0,255)
oct4 = random.randint(0,255)
return ".".join(map(str,([oct1,oct2,oct3,oct4])))
Word of warning, there are many other ip address ranges that are considered "private" make sure to review the list on IANA