Last modified: Apr 27, 2025 By Alexander Williams
Python Generate Random IP Addresses
Generating random IP addresses is useful for testing and simulations. Python makes it easy with built-in modules.
Why Generate Random IP Addresses?
Random IPs help in network testing, security research, and load testing. They simulate real-world scenarios without using real addresses.
You might also need random IPs for detecting private vs public IPs in your applications.
Generating Random IPv4 Addresses
IPv4 addresses have four octets (0-255) separated by dots. Here's how to generate them:
import random
def random_ipv4():
return ".".join(str(random.randint(0, 255)) for _ in range(4))
print(random_ipv4())
192.168.1.42
The random.randint
function generates numbers between 0 and 255. We join four numbers with dots to form an IP.
Generating Random IPv6 Addresses
IPv6 addresses are longer and use hexadecimal. Here's a generation method:
import random
def random_ipv6():
return ":".join("{:04x}".format(random.randint(0, 0xFFFF)) for _ in range(8))
print(random_ipv6())
3a4d:01f2:8c7e:12a9:fe34:5d67:b2c8:9e0f
This code creates eight 4-digit hex segments separated by colons. Each segment ranges from 0000 to FFFF.
Validating Generated IP Addresses
After generation, you may want to validate the IP addresses. Python's ipaddress
module can help.
Practical Applications
Random IPs are useful for:
- Testing network applications
- Simulating multiple clients
- Security penetration testing
For advanced networking, see our guide on handling multiple IP connections with AsyncIO.
Conclusion
Generating random IP addresses in Python is simple. The examples above create valid IPv4 and IPv6 addresses.
Remember to use these responsibly. Random IPs should only be used for testing and development purposes.