Developer Tools for Random Data Generation // v2.6.1
root@generate-random:~/ip-addresses/python$ _

Generate Random IP Addresses in Python

Complete code tutorial with examples and best practices

[ Code Example - Quick Summary ]

Language: Python

What: Generate random IPv4 and IPv6 addresses in Python using the ipaddress module and Faker library. Includes validation, private IP detection, and network testing utilities.

Try it: Use our interactive Ip-addresses generator or integrate this code into your Python application.

Generate random IPv4 and IPv6 addresses in Python using the ipaddress module and Faker library. Includes validation, private IP detection, and network testing utilities. Looking for other languages? Check our code examples in PHP , JavaScript , Java , C# , C++ , Ruby and Go or use our interactive web generator.

Python Code Example

import random
import ipaddress
from ipaddress import IPv4Address, IPv6Address

# Generate random IPv4 address
def random_ipv4():
    return str(IPv4Address(random.randint(0, 2**32 - 1)))

# Generate random private IPv4 (RFC 1918)
def random_private_ipv4():
    private_ranges = [
        ipaddress.ip_network('10.0.0.0/8'),
        ipaddress.ip_network('172.16.0.0/12'),
        ipaddress.ip_network('192.168.0.0/16'),
    ]
    network = random.choice(private_ranges)
    # Generate random IP within the network
    return str(IPv4Address(
        int(network.network_address) +
        random.randint(0, network.num_addresses - 1)
    ))

# Generate random public IPv4
def random_public_ipv4():
    while True:
        ip = IPv4Address(random.randint(0, 2**32 - 1))
        if not ip.is_private and not ip.is_loopback and not ip.is_reserved:
            return str(ip)

# Generate random IPv6 address
def random_ipv6():
    return str(IPv6Address(random.randint(0, 2**128 - 1)))

# Generate IPv4 with CIDR notation
def random_ipv4_with_cidr(min_cidr=8, max_cidr=32):
    ip = random_ipv4()
    cidr = random.randint(min_cidr, max_cidr)
    return f"{ip}/{cidr}"

# Validate IP address
def is_valid_ip(ip_string):
    try:
        ipaddress.ip_address(ip_string)
        return True
    except ValueError:
        return False

# Check if IP is private
def is_private_ip(ip_string):
    try:
        ip = ipaddress.ip_address(ip_string)
        return ip.is_private
    except ValueError:
        return False

# Generate multiple IP addresses
def generate_ip_addresses(count=10, ip_type='ipv4'):
    if ip_type == 'ipv6':
        return [random_ipv6() for _ in range(count)]
    else:
        return [random_ipv4() for _ in range(count)]

# Using Faker library (install: pip install faker)
# from faker import Faker
# fake = Faker()
# ipv4 = fake.ipv4()
# ipv4_private = fake.ipv4_private()
# ipv4_public = fake.ipv4_public()
# ipv6 = fake.ipv6()

# Usage examples
print("Random IPv4:", random_ipv4())
print("Private IPv4:", random_private_ipv4())
print("Public IPv4:", random_public_ipv4())
print("IPv6:", random_ipv6())
print("IPv4 with CIDR:", random_ipv4_with_cidr())
print("Batch:", ", ".join(generate_ip_addresses(5)))
print("Is valid:", is_valid_ip("192.168.1.1"))
print("Is private:", is_private_ip("192.168.1.1"))

[EXPLANATION]

Python's built-in ipaddress module provides excellent IP address handling. IPv4Address and IPv6Address classes create IP objects from integers (0 to 2³²-1 for IPv4, 0 to 2¹²⁸-1 for IPv6). The module includes useful properties like is_private, is_loopback, and is_reserved. For production use, the Faker library offers ipv4_private(), ipv4_public(), and ipv6() methods with more realistic distributions.

Expected Output

Random IPv4: 198.51.100.42
Private IPv4: 192.168.15.234
Public IPv4: 203.0.113.89
IPv6: 2001:db8:85a3::8a2e:370:7334
IPv4 with CIDR: 198.51.100.42/24
Batch: 203.0.113.15, 198.51.100.89, 192.0.2.45, 198.51.100.123, 203.0.113.67
Is valid: True
Is private: True

Common Use Cases

  • Generate test data for network security applications
  • Create mock server logs for data analysis pipelines
  • Test IP-based geolocation and routing algorithms
  • Populate network monitoring dashboards with test data
  • Generate realistic IP sets for penetration testing tools

Important Notes

  • Python's ipaddress module is part of the standard library (Python 3.3+)
  • IPv4Address and IPv6Address objects are immutable and hashable
  • Use Faker's fake.ipv4_private() for guaranteed RFC 1918 addresses
  • ip_network() can be used to work with entire subnets
  • For security testing, consider using secrets.randbelow() instead of random

Try Our Interactive Generator

Don't want to write code? Use our free web-based Ip-addresses generator with instant results.

TRY IP-ADDRESSES GENERATOR →