Skip to main content

How to Generate Random IP Addresses in Python

Generating random IP addresses can be useful for testing, simulations, or data anonymization.

This guide explores two methods for generating random IP addresses in Python: a custom function using the random module, and leveraging the Faker library for more realistic and varied IP address generation.

Generating Random IPv4 Addresses with random.randint()

To generate a random IPv4 address, you can generate four random numbers between 0 and 255, and join them with dots:

from random import randint

def generate_random_ip():
return '.'.join(str(randint(0, 255)) for _ in range(4))

random_ip = generate_random_ip()
print(random_ip) # Output: (A random IPv4 address, e.g., 178.166.111.80)
  • randint(0, 255) generates a random integer between 0 and 255 (inclusive), to get every octet in the IP address.
  • ('.'.join(...)) joins the four integers using the ' .' dot separator.
  • The generator expression (str(randint(0, 255)) for _ in range(4)) does this 4 times and converts each octet into string.

You can also use a loop to create a list of N random IP addresses.

Generating IP Addresses with the Faker Library

For more realistic IP addresses and various options, use the Faker library. To install it, use pip install Faker.

pip install Faker

Then, you can use the library:

Generating Public and Private IPv4 Addresses

from faker import Faker

fake = Faker()
ip_address = fake.ipv4()
print(ip_address) # Output (will vary): 173.188.6.176

Here are a few options for generating IP addresses:

  • The faker.ipv4() method returns a completely random IPv4 address.
  • The faker.ipv4_public() method returns a random public IPv4 address.
  • The faker.ipv4_private() method returns a random private IPv4 address.
from faker import Faker

fake = Faker()

ip_address = fake.ipv4_public()
print(ip_address) # Output (will vary): 188.104.196.45

ip_address = fake.ipv4_private()
print(ip_address) # Output (will vary): 172.18.1.190

Generating Random IPv6 Addresses

Use faker.ipv6() to generate random IPv6 addresses:

from faker import Faker
fake = Faker()

ip_address = fake.ipv6()
print(ip_address) # Output: 2528:a863:c2ff:413f:b8de:ff28:3f92:5b7