▶ Random Everything - 100+ Free Generators // v2.8.5
root@generate-random:~/ip-addresses/code-examples$ _

Random IP Address Code Examples

IPv4, IPv6, private ranges and CIDR in PHP, JavaScript, Python, Java, C#, C++, Ruby and Go

Every example below produces the same set: a random IPv4 address, a private address from the RFC 1918 blocks, a "public" address, a random IPv6 address, an IPv4 address with a CIDR prefix and a batch, plus a validity check. The guide explains which parts of the address space each function can land in and which ranges are meant for test data; each language section then shows the code and what is specific to that language. Prefer no code? The interactive IP address generator does the same in the browser.

What the random draw covers

An IPv4 address is a 32-bit number written as four octets from 0 to 255, so there are 232 = 4,294,967,296 of them. Drawing each octet uniformly covers the whole space, including blocks that never appear as a host on the internet: 0.0.0.0/8, loopback 127.0.0.0/8, multicast 224.0.0.0/4 and the reserved 240.0.0.0/4. Together with the private blocks that is roughly one draw in seven. That is what you want for parser and validator tests, and not what you want for realistic logs.

IPv6 addresses are 128 bits written as eight groups of four hex digits. A uniform 128-bit draw falls inside the global unicast block 2000::/3 only one time in eight. The examples print the full form (2001:0db8:0000:…); the canonical text form from RFC 5952 is lowercase with leading zeros dropped and the longest run of zero groups written as ::, so 2001:db8::1.

Private, public and documentation ranges

  • Private (RFC 1918): 10.0.0.0/8 (16,777,216 addresses), 172.16.0.0/12 (second octet 16–31, 1,048,576 addresses) and 192.168.0.0/16 (65,536). The examples first pick one of the three blocks with equal chance, so any single 192.168 address is 256 times more likely than any single 10.x address. That gives variety, not a uniform draw over private space.
  • "Public": most examples only exclude RFC 1918, loopback and 0.0.0.0/8. Shared address space 100.64.0.0/10 (RFC 6598, carrier-grade NAT), link-local 169.254.0.0/16, multicast and 240.0.0.0/4 still get through. Libraries that know the IANA special-purpose registry (Python's is_global, Go's netip) filter these properly.
  • Documentation: RFC 5737 sets aside 192.0.2.0/24, 198.51.100.0/24 and 203.0.113.0/24, and RFC 3849 sets aside 2001:db8::/32 for IPv6. Use these for anything that leaves your machine: screenshots, published sample logs, bug reports, data sent to a third-party geolocation API. A random public address belongs to somebody.

Secure or non-secure random?

For test data the fast default generator is the right tool, and seeding it makes a fake log file identical on every run. Unpredictability matters only when the address bits are an identifier someone should not guess: IPv6 temporary interface IDs (RFC 8981) and the 40-bit Global ID of a unique local prefix in fd00::/8 (RFC 4193) are meant to be random. Generate those from the secure source of your language.

Common mistakes

  • Classifying addresses with string patterns. ^172\.1 also matches 172.1.x.x and 172.100.x.x. Compare numerically or use the standard library parser (ipaddress, net/netip, IPAddr, System.Net.IPNetwork).
  • Host bits in CIDR notation. A random address plus a random prefix, such as 198.51.100.42/24, describes a host inside a network, not the network itself, which is 198.51.100.0/24. Strict parsers reject the first form as a network; mask the host bits when you need a subnet.
  • Zero-padding octets. 010.001.002.003 is read as octal by inet_aton-style parsers and rejected by Python 3.9.5+ and Go 1.17+. Never pad IPv4 octets; padded IPv6 groups are fine, they are simply the full form.
  • Sending traffic to random addresses. Generated public addresses are for storing and parsing, never for pinging or scanning.

Common Use Cases

  • Sample access logs for SIEM, monitoring and analytics dashboards
  • Tests for rate limiting, allowlists, denylists and other IP-based access control
  • Geolocation and IP-to-country lookup tests
  • Mock API responses and database seeds with client IP or device network fields
  • Parser, validator and subnet-calculation tests for IPv4, IPv6 and CIDR input

Random IP Address Code Examples in PHP

Generate random IPv4 and IPv6 addresses in PHP for network testing, API mocking, and development. This guide covers public/private IP ranges, CIDR notation, and validation.

<?php
// Generate random IPv4 address
function randomIpv4() {
    return sprintf(
        "%d.%d.%d.%d",
        mt_rand(0, 255),
        mt_rand(0, 255),
        mt_rand(0, 255),
        mt_rand(0, 255)
    );
}

// Generate random private IPv4 (RFC 1918)
function randomPrivateIpv4() {
    $ranges = [
        ["10", mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255)],
        ["172", mt_rand(16, 31), mt_rand(0, 255), mt_rand(0, 255)],
        ["192", "168", mt_rand(0, 255), mt_rand(0, 255)],
    ];
    $ip = $ranges[array_rand($ranges)];
    return implode(".", $ip);
}

// Generate random public IPv4 (avoiding private ranges)
function randomPublicIpv4() {
    do {
        $ip = randomIpv4();
    } while (
        preg_match("/^10\./", $ip) ||
        preg_match("/^172\.(1[6-9]|2[0-9]|3[01])\./", $ip) ||
        preg_match("/^192\.168\./", $ip) ||
        preg_match("/^127\./", $ip) ||
        preg_match("/^0\./", $ip)
    );
    return $ip;
}

// Generate random IPv6 address
function randomIpv6() {
    $parts = [];
    for ($i = 0; $i < 8; $i++) {
        $parts[] = sprintf("%04x", mt_rand(0, 0xFFFF));
    }
    return implode(":", $parts);
}

// Generate IPv4 with CIDR notation
function randomIpv4WithCidr($minCidr = 8, $maxCidr = 32) {
    $ip = randomIpv4();
    $cidr = mt_rand($minCidr, $maxCidr);
    return "$ip/$cidr";
}

// Validate IPv4 address
function isValidIpv4($ip) {
    return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false;
}

// Validate IPv6 address
function isValidIpv6($ip) {
    return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false;
}

// Generate multiple IP addresses
function generateIpAddresses($count = 10, $type = "ipv4") {
    $ips = [];
    for ($i = 0; $i < $count; $i++) {
        $ips[] = $type === "ipv6" ? randomIpv6() : randomIpv4();
    }
    return $ips;
}

// Usage examples
echo "Random IPv4: " . randomIpv4() . "\n";
echo "Private IPv4: " . randomPrivateIpv4() . "\n";
echo "Public IPv4: " . randomPublicIpv4() . "\n";
echo "IPv6: " . randomIpv6() . "\n";
echo "IPv4 with CIDR: " . randomIpv4WithCidr() . "\n";

$batch = generateIpAddresses(5);
echo "Batch: " . implode(", ", $batch) . "\n";

How it works in PHP

This implementation uses mt_rand() for generating random octets (0-255) and sprintf() for formatting IPv4 addresses. For private IPs, it follows RFC 1918 ranges: 10.0.0.0/8, 172.16.0.0/12, and 192.168.0.0/16. IPv6 addresses use 8 groups of 4 hexadecimal digits. The filter_var() function with FILTER_VALIDATE_IP validates IP formats. CIDR notation adds a subnet mask (e.g., /24) for network testing.

Sample output

Random IPv4: 198.51.100.42
Private IPv4: 192.168.15.234
Public IPv4: 203.0.113.89
IPv6: 2001:0db8:85a3:0000:0000:8a2e:0370: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

PHP notes

  • filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) rejects private and reserved addresses without a regex.
  • long2ip(random_int(0, 0xFFFFFFFF)) draws a whole IPv4 address in one call on 64-bit PHP.
  • inet_ntop(inet_pton($ip)) turns a full IPv6 address into its compressed form, such as 2001:db8::1.

Random IP Address Code Examples in JavaScript

Generate random IPv4 and IPv6 addresses in JavaScript for frontend and Node.js applications. Includes validation, private IP ranges, and network testing utilities.

// Generate random IPv4 address
function randomIpv4() {
    return Array.from({length: 4}, () =>
        Math.floor(Math.random() * 256)
    ).join('.');
}

// Generate random private IPv4 (RFC 1918)
function randomPrivateIpv4() {
    const ranges = [
        [10, () => Math.floor(Math.random() * 256),
            () => Math.floor(Math.random() * 256),
            () => Math.floor(Math.random() * 256)],
        [172, () => Math.floor(Math.random() * 16) + 16,
            () => Math.floor(Math.random() * 256),
            () => Math.floor(Math.random() * 256)],
        [192, 168, () => Math.floor(Math.random() * 256),
            () => Math.floor(Math.random() * 256)],
    ];

    const range = ranges[Math.floor(Math.random() * ranges.length)];
    return range.map(val => typeof val === 'function' ? val() : val).join('.');
}

// Generate random public IPv4
function randomPublicIpv4() {
    let ip;
    do {
        ip = randomIpv4();
    } while (isPrivateIp(ip));
    return ip;
}

// Check if IP is private
function isPrivateIp(ip) {
    return /^10\./.test(ip) ||
           /^172\.(1[6-9]|2[0-9]|3[01])\./.test(ip) ||
           /^192\.168\./.test(ip) ||
           /^127\./.test(ip) ||
           /^0\./.test(ip);
}

// Generate random IPv6 address
function randomIpv6() {
    return Array.from({length: 8}, () =>
        Math.floor(Math.random() * 0x10000).toString(16).padStart(4, '0')
    ).join(':');
}

// Generate IPv4 with CIDR notation
function randomIpv4WithCidr(minCidr = 8, maxCidr = 32) {
    const ip = randomIpv4();
    const cidr = Math.floor(Math.random() * (maxCidr - minCidr + 1)) + minCidr;
    return `${ip}/${cidr}`;
}

// Validate IPv4 address
function isValidIpv4(ip) {
    const pattern = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
    return pattern.test(ip);
}

// Generate multiple IP addresses
function generateIpAddresses(count = 10, type = 'ipv4') {
    return Array.from({length: count}, () =>
        type === 'ipv6' ? randomIpv6() : randomIpv4()
    );
}

// Usage examples
console.log("Random IPv4:", randomIpv4());
console.log("Private IPv4:", randomPrivateIpv4());
console.log("Public IPv4:", randomPublicIpv4());
console.log("IPv6:", randomIpv6());
console.log("IPv4 with CIDR:", randomIpv4WithCidr());
console.log("Batch:", generateIpAddresses(5).join(', '));

How it works in JavaScript

This implementation uses Math.random() with Array.from() for generating IP octets. IPv4 addresses use 4 octets (0-255), while IPv6 uses 8 groups of 4 hexadecimal digits. Private IP detection uses regex to match RFC 1918 ranges. The padStart() method ensures IPv6 groups are zero-padded to 4 digits. For Node.js, you can use the built-in net module for validation, or packages like ip or faker for more features.

Sample output

Random IPv4: 198.51.100.42
Private IPv4: 192.168.15.234
Public IPv4: 203.0.113.89
IPv6: 2001:0db8:85a3:0000:0000:8a2e:0370: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

JavaScript notes

  • Node's net.isIPv4() and net.isIPv6() validate, and net.BlockList (Node 15+) checks subnet membership: addSubnet('10.0.0.0', 8), then check(ip).
  • crypto.getRandomValues(new Uint8Array(4)) gives four secure octets in browsers and Node.
  • @faker-js/faker v9 accepts faker.internet.ipv4({ cidrBlock: '192.0.2.0/24' }) or { network: 'private-a' } to stay inside a range.

Random IP Address Code Examples in Python

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

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 ip.is_global and not ip.is_multicast:
            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"))

How it works in Python

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.

Sample 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

Python notes

  • In ipaddress, the documentation blocks count as is_private, and 100.64.0.0/10 is neither private nor global; is_global is the reliable "public" test.
  • ip_network('198.51.100.42/24') raises ValueError because host bits are set; pass strict=False to get the network.
  • str(IPv6Address(n)) is already the RFC 5952 compressed form; .exploded gives all eight groups.
  • Faker has ipv4_public(), ipv4_private() and ipv4(network=True) for an address with a prefix.

Random IP Address Code Examples in Java

Generate random IPv4 and IPv6 addresses in Java using Random and InetAddress. Includes validation, RFC 1918 private ranges, and integration with JavaFaker library.

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class IpAddressGenerator {
    private static final Random random = new Random();

    // Generate random IPv4 address
    public static String randomIpv4() {
        return String.format("%d.%d.%d.%d",
            random.nextInt(256),
            random.nextInt(256),
            random.nextInt(256),
            random.nextInt(256)
        );
    }

    // Generate random private IPv4 (RFC 1918)
    public static String randomPrivateIpv4() {
        int range = random.nextInt(3);
        switch (range) {
            case 0: // 10.0.0.0/8
                return String.format("10.%d.%d.%d",
                    random.nextInt(256),
                    random.nextInt(256),
                    random.nextInt(256));
            case 1: // 172.16.0.0/12
                return String.format("172.%d.%d.%d",
                    random.nextInt(16) + 16,
                    random.nextInt(256),
                    random.nextInt(256));
            default: // 192.168.0.0/16
                return String.format("192.168.%d.%d",
                    random.nextInt(256),
                    random.nextInt(256));
        }
    }

    // Generate random public IPv4
    public static String randomPublicIpv4() {
        String ip;
        do {
            ip = randomIpv4();
        } while (isPrivateIp(ip));
        return ip;
    }

    // Check if IP is private
    public static boolean isPrivateIp(String ip) {
        return ip.matches("^10\\..*") ||
               ip.matches("^172\\.(1[6-9]|2[0-9]|3[01])\\..*") ||
               ip.matches("^192\\.168\\..*") ||
               ip.matches("^127\\..*") ||
               ip.matches("^0\\..*");
    }

    // Generate random IPv6 address
    public static String randomIpv6() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 8; i++) {
            if (i > 0) sb.append(":");
            sb.append(String.format("%04x", random.nextInt(0x10000)));
        }
        return sb.toString();
    }

    // Generate IPv4 with CIDR notation
    public static String randomIpv4WithCidr(int minCidr, int maxCidr) {
        String ip = randomIpv4();
        int cidr = random.nextInt(maxCidr - minCidr + 1) + minCidr;
        return String.format("%s/%d", ip, cidr);
    }

    // Validate IPv4 address using InetAddress
    public static boolean isValidIp(String ip) {
        try {
            InetAddress.getByName(ip);
            return true;
        } catch (UnknownHostException e) {
            return false;
        }
    }

    // Generate multiple IP addresses
    public static List<String> generateIpAddresses(int count, String type) {
        List<String> ips = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            ips.add(type.equals("ipv6") ? randomIpv6() : randomIpv4());
        }
        return ips;
    }

    // Using JavaFaker library (add dependency: com.github.javafaker:javafaker:1.0.2)
    // import com.github.javafaker.Faker;
    // Faker faker = new Faker();
    // String ipv4 = faker.internet().ipV4Address();
    // String ipv6 = faker.internet().ipV6Address();
    // String privateIp = faker.internet().privateIpV4Address();
    // String publicIp = faker.internet().publicIpV4Address();

    public static void main(String[] args) {
        System.out.println("Random IPv4: " + randomIpv4());
        System.out.println("Private IPv4: " + randomPrivateIpv4());
        System.out.println("Public IPv4: " + randomPublicIpv4());
        System.out.println("IPv6: " + randomIpv6());
        System.out.println("IPv4 with CIDR: " + randomIpv4WithCidr(8, 32));
        System.out.println("Batch: " + String.join(", ", generateIpAddresses(5, "ipv4")));
        System.out.println("Is valid: " + isValidIp("192.168.1.1"));
    }
}

How it works in Java

This implementation uses Random.nextInt(256) for generating octets and String.format() for formatting. Java's InetAddress class provides validation but doesn't directly support random generation. Private IP ranges follow RFC 1918. The JavaFaker library provides convenient methods like ipV4Address(), ipV6Address(), privateIpV4Address(), and publicIpV4Address() for production testing frameworks.

Sample output

Random IPv4: 198.51.100.42
Private IPv4: 192.168.15.234
Public IPv4: 203.0.113.89
IPv6: 2001:0db8:85a3:0000:0000:8a2e:0370: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

Java notes

  • InetAddress.getByName() resolves hostnames through DNS, so isValidIp("example.com") returns true and can block; Guava's InetAddresses.isInetAddress() checks literals only.
  • InetAddress.getByAddress(bytes) builds an address from 4 or 16 random bytes without any lookup.
  • isSiteLocalAddress() is true for the RFC 1918 blocks; isLoopbackAddress(), isLinkLocalAddress() and isMulticastAddress() cover the rest.

Random IP Address Code Examples in C#

Generate random IPv4 and IPv6 addresses in C# using Random and IPAddress. Includes validation, RFC 1918 private ranges, and integration with Bogus library for .NET testing.

using System;
using System.Net;
using System.Linq;
using System.Text.RegularExpressions;

public class IpAddressGenerator
{
    private static readonly Random random = new Random();

    // Generate random IPv4 address
    public static string RandomIpv4()
    {
        return $"{random.Next(256)}.{random.Next(256)}.{random.Next(256)}.{random.Next(256)}";
    }

    // Generate random private IPv4 (RFC 1918)
    public static string RandomPrivateIpv4()
    {
        var ranges = new Func<string>[]
        {
            () => $"10.{random.Next(256)}.{random.Next(256)}.{random.Next(256)}",
            () => $"172.{random.Next(16, 32)}.{random.Next(256)}.{random.Next(256)}",
            () => $"192.168.{random.Next(256)}.{random.Next(256)}"
        };
        return ranges[random.Next(ranges.Length)]();
    }

    // Generate random public IPv4
    public static string RandomPublicIpv4()
    {
        string ip;
        do
        {
            ip = RandomIpv4();
        } while (IsPrivateIp(ip));
        return ip;
    }

    // Check if IP is private
    public static bool IsPrivateIp(string ip)
    {
        return Regex.IsMatch(ip, @"^10\.") ||
               Regex.IsMatch(ip, @"^172\.(1[6-9]|2[0-9]|3[01])\.") ||
               Regex.IsMatch(ip, @"^192\.168\.") ||
               Regex.IsMatch(ip, @"^127\.") ||
               Regex.IsMatch(ip, @"^0\.");
    }

    // Generate random IPv6 address
    public static string RandomIpv6()
    {
        var groups = Enumerable.Range(0, 8)
            .Select(_ => random.Next(0x10000).ToString("x4"));
        return string.Join(":", groups);
    }

    // Generate IPv4 with CIDR notation
    public static string RandomIpv4WithCidr(int minCidr = 8, int maxCidr = 32)
    {
        var ip = RandomIpv4();
        var cidr = random.Next(minCidr, maxCidr + 1);
        return $"{ip}/{cidr}";
    }

    // Validate IP address using IPAddress
    public static bool IsValidIp(string ipString)
    {
        return IPAddress.TryParse(ipString, out _);
    }

    // Generate multiple IP addresses
    public static string[] GenerateIpAddresses(int count = 10, string type = "ipv4")
    {
        return Enumerable.Range(0, count)
            .Select(_ => type == "ipv6" ? RandomIpv6() : RandomIpv4())
            .ToArray();
    }

    // Using Bogus library (Install-Package Bogus)
    // using Bogus;
    // var faker = new Faker();
    // string ipv4 = faker.Internet.Ip();
    // string ipv6 = faker.Internet.Ipv6();

    public static void Main()
    {
        Console.WriteLine($"Random IPv4: {RandomIpv4()}");
        Console.WriteLine($"Private IPv4: {RandomPrivateIpv4()}");
        Console.WriteLine($"Public IPv4: {RandomPublicIpv4()}");
        Console.WriteLine($"IPv6: {RandomIpv6()}");
        Console.WriteLine($"IPv4 with CIDR: {RandomIpv4WithCidr()}");
        Console.WriteLine($"Batch: {string.Join(", ", GenerateIpAddresses(5))}");
        Console.WriteLine($"Is valid: {IsValidIp("192.168.1.1")}");
    }
}

How it works in C#

This C# implementation uses Random.Next(256) for generating octets and string interpolation for formatting. The IPAddress class from System.Net provides validation via TryParse(). LINQ's Enumerable.Range() simplifies batch generation. The Bogus library offers Internet.Ip() and Internet.Ipv6() methods, integrating seamlessly with xUnit, NUnit, and MSTest frameworks for .NET testing.

Sample output

Random IPv4: 198.51.100.42
Private IPv4: 192.168.15.234
Public IPv4: 203.0.113.89
IPv6: 2001:0db8:85a3:0000:0000:8a2e:0370: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

C# notes

  • IPAddress.TryParse() accepts legacy shorthand: "10.1" parses as 10.0.0.1, so it is too lenient as a strict format check.
  • new IPAddress(RandomNumberGenerator.GetBytes(16)) (.NET 6+) gives a secure random IPv6 address, and its ToString() is compressed.
  • .NET 8 adds System.Net.IPNetwork: IPNetwork.Parse("10.0.0.0/8").Contains(ip).

Random IP Address Code Examples in C++

Generate random IPv4 and IPv6 addresses in C++ using std::random and string formatting. Includes private IP ranges, validation, and network testing utilities.

#include <iostream>
#include <random>
#include <sstream>
#include <iomanip>
#include <vector>
#include <regex>

class IpAddressGenerator {
private:
    std::mt19937 rng;
    std::uniform_int_distribution<int> octet_dist;
    std::uniform_int_distribution<int> hex_dist;

public:
    IpAddressGenerator() :
        rng(std::random_device{}()),
        octet_dist(0, 255),
        hex_dist(0, 0xFFFF) {}

    // Generate random IPv4 address
    std::string randomIpv4() {
        std::ostringstream oss;
        oss << octet_dist(rng) << "."
            << octet_dist(rng) << "."
            << octet_dist(rng) << "."
            << octet_dist(rng);
        return oss.str();
    }

    // Generate random private IPv4 (RFC 1918)
    std::string randomPrivateIpv4() {
        std::uniform_int_distribution<int> range_dist(0, 2);
        int range = range_dist(rng);

        std::ostringstream oss;
        switch (range) {
            case 0: // 10.0.0.0/8
                oss << "10." << octet_dist(rng) << "."
                    << octet_dist(rng) << "." << octet_dist(rng);
                break;
            case 1: { // 172.16.0.0/12
                std::uniform_int_distribution<int> range172(16, 31);
                oss << "172." << range172(rng) << "."
                    << octet_dist(rng) << "." << octet_dist(rng);
                break;
            }
            default: // 192.168.0.0/16
                oss << "192.168." << octet_dist(rng) << "." << octet_dist(rng);
                break;
        }
        return oss.str();
    }

    // Check if IP is private
    bool isPrivateIp(const std::string& ip) {
        std::regex private_patterns[] = {
            std::regex("^10\\."),
            std::regex("^172\\.(1[6-9]|2[0-9]|3[01])\\."),
            std::regex("^192\\.168\\."),
            std::regex("^127\\."),
            std::regex("^0\\.")
        };

        for (const auto& pattern : private_patterns) {
            if (std::regex_search(ip, pattern)) {
                return true;
            }
        }
        return false;
    }

    // Generate random public IPv4
    std::string randomPublicIpv4() {
        std::string ip;
        do {
            ip = randomIpv4();
        } while (isPrivateIp(ip));
        return ip;
    }

    // Generate random IPv6 address
    std::string randomIpv6() {
        std::ostringstream oss;
        for (int i = 0; i < 8; ++i) {
            if (i > 0) oss << ":";
            oss << std::hex << std::setw(4) << std::setfill('0')
                << hex_dist(rng);
        }
        return oss.str();
    }

    // Generate IPv4 with CIDR notation
    std::string randomIpv4WithCidr(int minCidr = 8, int maxCidr = 32) {
        std::uniform_int_distribution<int> cidr_dist(minCidr, maxCidr);
        std::ostringstream oss;
        oss << randomIpv4() << "/" << cidr_dist(rng);
        return oss.str();
    }

    // Generate multiple IP addresses
    std::vector<std::string> generateIpAddresses(int count = 10, const std::string& type = "ipv4") {
        std::vector<std::string> ips;
        for (int i = 0; i < count; ++i) {
            ips.push_back(type == "ipv6" ? randomIpv6() : randomIpv4());
        }
        return ips;
    }
};

int main() {
    IpAddressGenerator generator;

    std::cout << "Random IPv4: " << generator.randomIpv4() << std::endl;
    std::cout << "Private IPv4: " << generator.randomPrivateIpv4() << std::endl;
    std::cout << "Public IPv4: " << generator.randomPublicIpv4() << std::endl;
    std::cout << "IPv6: " << generator.randomIpv6() << std::endl;
    std::cout << "IPv4 with CIDR: " << generator.randomIpv4WithCidr() << std::endl;

    auto batch = generator.generateIpAddresses(5);
    std::cout << "Batch: ";
    for (size_t i = 0; i < batch.size(); ++i) {
        if (i > 0) std::cout << ", ";
        std::cout << batch[i];
    }
    std::cout << std::endl;

    return 0;
}

How it works in C++

This C++ implementation uses std::mt19937 Mersenne Twister for high-quality random generation and std::uniform_int_distribution for generating octets (0-255) and IPv6 groups (0-0xFFFF). std::ostringstream handles string formatting, with std::setw(4) and std::setfill('0') for zero-padded hexadecimal IPv6 groups. std::regex provides private IP pattern matching. For network applications, consider using Boost.Asio's boost::asio::ip::address for validation.

Sample output

Random IPv4: 198.51.100.42
Private IPv4: 192.168.15.234
Public IPv4: 203.0.113.89
IPv6: 2001:0db8:85a3:0000:0000:8a2e:0370: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

C++ notes

  • The standard library has no IP type: inet_pton and inet_ntop (<arpa/inet.h>, or <ws2tcpip.h> on Windows) validate and produce canonical text.
  • A variable declared inside a case needs its own braces, or the jump to the next label crosses its initialization and does not compile.
  • In Boost.Asio, ip::make_address() replaces the deprecated address::from_string().

Random IP Address Code Examples in Ruby

Generate random IPv4 and IPv6 addresses in Ruby using rand and IPAddr. Includes validation, RFC 1918 private ranges, and integration with Faker gem for Rails testing.

require 'ipaddr'

# Generate random IPv4 address
def random_ipv4
  Array.new(4) { rand(0..255) }.join('.')
end

# Generate random private IPv4 (RFC 1918)
def random_private_ipv4
  ranges = [
    -> { "10.#{rand(0..255)}.#{rand(0..255)}.#{rand(0..255)}" },
    -> { "172.#{rand(16..31)}.#{rand(0..255)}.#{rand(0..255)}" },
    -> { "192.168.#{rand(0..255)}.#{rand(0..255)}" }
  ]
  ranges.sample.call
end

# Check if IP is private
def private_ip?(ip)
  return true if ip.start_with?('10.')
  return true if ip.match?(/^172\.(1[6-9]|2[0-9]|3[01])\./)
  return true if ip.start_with?('192.168.')
  return true if ip.start_with?('127.')
  return true if ip.start_with?('0.')
  false
end

# Generate random public IPv4
def random_public_ipv4
  loop do
    ip = random_ipv4
    return ip unless private_ip?(ip)
  end
end

# Generate random IPv6 address
def random_ipv6
  Array.new(8) { rand(0..0xFFFF).to_s(16).rjust(4, '0') }.join(':')
end

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

# Validate IP address using IPAddr
def valid_ip?(ip_string)
  IPAddr.new(ip_string)
  true
rescue IPAddr::InvalidAddressError
  false
end

# Check if IP is private using IPAddr
def private_ip_addr?(ip_string)
  ip = IPAddr.new(ip_string)
  ip.private?
rescue IPAddr::InvalidAddressError
  false
end

# Generate multiple IP addresses
def generate_ip_addresses(count = 10, type: :ipv4)
  count.times.map do
    type == :ipv6 ? random_ipv6 : random_ipv4
  end
end

# Using Faker gem (add to Gemfile: gem 'faker')
# require 'faker'
# ipv4 = Faker::Internet.ip_v4_address
# ipv4_private = Faker::Internet.private_ip_v4_address
# ipv4_public = Faker::Internet.public_ip_v4_address
# ipv6 = Faker::Internet.ip_v6_address

# Usage examples
puts "Random IPv4: #{random_ipv4}"
puts "Private IPv4: #{random_private_ipv4}"
puts "Public IPv4: #{random_public_ipv4}"
puts "IPv6: #{random_ipv6}"
puts "IPv4 with CIDR: #{random_ipv4_with_cidr}"
puts "Batch: #{generate_ip_addresses(5).join(', ')}"
puts "Is valid: #{valid_ip?('192.168.1.1')}"
puts "Is private: #{private_ip_addr?('192.168.1.1')}"

How it works in Ruby

Ruby's Array.new(4) { rand(0..255) } creates 4 random octets, joined with dots. The built-in IPAddr class provides validation and the private? method for detecting RFC 1918 addresses. rand(0..255) generates inclusive random numbers. For IPv6, to_s(16) converts to hexadecimal and rjust(4, '0') zero-pads to 4 digits. The Faker gem offers convenient methods like ip_v4_address, private_ip_v4_address, and ip_v6_address for Rails and RSpec testing.

Sample output

Random IPv4: 198.51.100.42
Private IPv4: 192.168.15.234
Public IPv4: 203.0.113.89
IPv6: 2001:0db8:85a3:0000:0000:8a2e:0370: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

Ruby notes

  • IPAddr#private? (Ruby 2.5+) covers RFC 1918 and IPv6 fc00::/7 only; loopback and link-local need loopback? and link_local?.
  • IPAddr.new(rand(2**32), Socket::AF_INET) builds an address from an integer; to_s compresses IPv6, to_string prints all groups.
  • Faker's private_ip_v4_address also returns addresses from non-RFC 1918 blocks such as 192.0.0.0/24 and 100.64.0.0/10.

Random IP Address Code Examples in Go

Generate random IPv4 and IPv6 addresses in Go using math/rand and net.IP. Includes validation, RFC 1918 private ranges, and network testing utilities.

package main

import (
    "fmt"
    "math/rand"
    "net"
    "regexp"
)

// Generate random IPv4 address
func randomIPv4() string {
    return fmt.Sprintf("%d.%d.%d.%d",
        rand.Intn(256),
        rand.Intn(256),
        rand.Intn(256),
        rand.Intn(256))
}

// Generate random private IPv4 (RFC 1918)
func randomPrivateIPv4() string {
    switch rand.Intn(3) {
    case 0: // 10.0.0.0/8
        return fmt.Sprintf("10.%d.%d.%d",
            rand.Intn(256),
            rand.Intn(256),
            rand.Intn(256))
    case 1: // 172.16.0.0/12
        return fmt.Sprintf("172.%d.%d.%d",
            rand.Intn(16)+16,
            rand.Intn(256),
            rand.Intn(256))
    default: // 192.168.0.0/16
        return fmt.Sprintf("192.168.%d.%d",
            rand.Intn(256),
            rand.Intn(256))
    }
}

// Check if IP is private
func isPrivateIP(ip string) bool {
    patterns := []string{
        `^10\.`,
        `^172\.(1[6-9]|2[0-9]|3[01])\.`,
        `^192\.168\.`,
        `^127\.`,
        `^0\.`,
    }

    for _, pattern := range patterns {
        matched, _ := regexp.MatchString(pattern, ip)
        if matched {
            return true
        }
    }
    return false
}

// Generate random public IPv4
func randomPublicIPv4() string {
    var ip string
    for {
        ip = randomIPv4()
        if !isPrivateIP(ip) {
            break
        }
    }
    return ip
}

// Generate random IPv6 address
func randomIPv6() string {
    parts := make([]string, 8)
    for i := 0; i < 8; i++ {
        parts[i] = fmt.Sprintf("%04x", rand.Intn(0x10000))
    }
    return fmt.Sprintf("%s:%s:%s:%s:%s:%s:%s:%s",
        parts[0], parts[1], parts[2], parts[3],
        parts[4], parts[5], parts[6], parts[7])
}

// Generate IPv4 with CIDR notation
func randomIPv4WithCIDR(minCIDR, maxCIDR int) string {
    ip := randomIPv4()
    cidr := rand.Intn(maxCIDR-minCIDR+1) + minCIDR
    return fmt.Sprintf("%s/%d", ip, cidr)
}

// Validate IP address using net.ParseIP
func isValidIP(ipString string) bool {
    return net.ParseIP(ipString) != nil
}

// Check if IP is private using net package
func isPrivateIPNet(ipString string) bool {
    ip := net.ParseIP(ipString)
    if ip == nil {
        return false
    }

    privateRanges := []string{
        "10.0.0.0/8",
        "172.16.0.0/12",
        "192.168.0.0/16",
        "127.0.0.0/8",
    }

    for _, cidr := range privateRanges {
        _, subnet, _ := net.ParseCIDR(cidr)
        if subnet.Contains(ip) {
            return true
        }
    }
    return false
}

// Generate multiple IP addresses
func generateIPAddresses(count int, ipType string) []string {
    ips := make([]string, count)
    for i := 0; i < count; i++ {
        if ipType == "ipv6" {
            ips[i] = randomIPv6()
        } else {
            ips[i] = randomIPv4()
        }
    }
    return ips
}

func main() {
    fmt.Println("Random IPv4:", randomIPv4())
    fmt.Println("Private IPv4:", randomPrivateIPv4())
    fmt.Println("Public IPv4:", randomPublicIPv4())
    fmt.Println("IPv6:", randomIPv6())
    fmt.Println("IPv4 with CIDR:", randomIPv4WithCIDR(8, 32))

    batch := generateIPAddresses(5, "ipv4")
    fmt.Printf("Batch: %s\n", batch)

    fmt.Println("Is valid:", isValidIP("192.168.1.1"))
    fmt.Println("Is private:", isPrivateIPNet("192.168.1.1"))
}

How it works in Go

Go's rand.Intn(256) generates random octets, and fmt.Sprintf() formats IP addresses. The net package provides net.ParseIP() for validation and net.ParseCIDR() for subnet operations. The Contains() method checks if an IP belongs to a subnet, useful for detecting private ranges. Since Go 1.20 the global source is seeded automatically, so no rand.Seed call is needed. In math/rand/v2 (Go 1.22+) the same call is rand.IntN(256).

Sample output

Random IPv4: 198.51.100.42
Private IPv4: 192.168.15.234
Public IPv4: 203.0.113.89
IPv6: 2001:0db8:85a3:0000:0000:8a2e:0370: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

Go notes

  • net/netip (Go 1.18+) has a comparable value type: netip.AddrFrom4([4]byte{…}), then IsPrivate() or IsGlobalUnicast().
  • Since Go 1.17, net.ParseIP rejects IPv4 octets with leading zeros, and net.IP has IsPrivate().
  • Fill a 16-byte slice with crypto/rand.Read for secure IPv6 interface identifiers.

Try the Interactive Generator

Need values right now rather than code? The IP address generator runs in the browser and exports to TXT, CSV or JSON.

OPEN THE IP ADDRESS GENERATOR →