This tutorial provides you with techniques to generate random IP addresses in Python. It’ll also walk you through the concept of IP addresses and describe the two main versions (IPv4 and IPv6). After that,
Understand Random IP Address Generation in Python
Let’s learn how to create a random IP address generator in Python. We’ll highlight potential use cases, and give you practical examples to help you understand. You’ll get the ready-to-use code that you can directly use in your Python programs.
Also Read:
Python Generate Random Email
Python Generate Random Image
Before diving into generating random IP addresses, it’s essential to have a basic understanding of what an IP address is.
What is an IP Address?
An IP (Internet Protocol) address is a numerical label assigned to each device participating in a computer network that uses the Internet Protocol for communication. IPv4 addresses consist of four sets of numbers separated by dots, while IPv6 addresses are longer and include both numbers and letters.
An IP address acts as a unique identifier for devices on a network, similar to a home address in the real world. It allows devices to communicate and exchange data across the internet. There are two main IP address versions:
IPv4 (Internet Protocol version 4)
The most widely used version consists of four octets (sections) separated by periods, with each octet ranging from 0 to 255.
IPv4 addresses follow the format A.B.C.D, where each of A, B, C, and D can range from 0 to 255. For example, the following is a common IPv4 address.
# A common IPv4 Address
192.168.1.1
IPv6 (Internet Protocol version 6)
The newer version, is designed to address the limitations of IPv4 and offers a significantly larger address space. It uses eight 16-bit hexadecimal groups separated by colons.
IPv6 addresses have a more complex structure, represented as eight groups of four hexadecimal digits separated by colons. An example of an IPv6 address is:
# A sample IPv6 Address
2001:0db8:85a3:0000:0000:8a2e:0370:7334
Now that we have a basic understanding of IP addresses, let’s explore different methods to generate random ones using Python.
Generating Random IPv4 Addresses
We’ll describe two methods to generate random IP addresses. Both methods will use the Python random module to generate random numbers. We’ll use those numerals as the octet values for our IP address.
Let’s discuss the first approach to generate a random IPv4 address.
By using the random
Module
It works in two parts. In the first part, we’ll utilize the random number functions to produce unique values. Secondly, we’ll write our logic to form an IP IPv4 address type structure and fill in the octets by using random numbers.
"""
Python Code to Generate a Random IPv4 Address
"""
import random as rand
def gen_rand_ipv4():
"""Generates a random IPv4 address."""
octets = [str(rand.randint(0, 255)) for _ in range(4)]
return ".".join(octets)
# Example usage
random_ip = gen_rand_ipv4()
print(random_ip)
Whenever you run the above code, it produces a new and unique IPv4 address.
Run#1 167.226.10.221
Run#2 106.208.76.128
Here is a line-by-line explanation of the above code.
Explanation:
- Import
random
module: This module gives us functions to produce random numbers. - Define
gen_rand_ipv4
function: This function encapsulates the logic for generating a random IP address. - Generate random octets: The list comprehension
[str(rand.randint(0, 255)) for _ in range(4)]
returns four random integers between 0 and 255, each representing an octet. They are then converted to strings usingstr()
. - Join octets: The method
join
with “.” as the separator combines the 4 octet strings into a single string, forming the complete IP address. - Example usage: The
random_ip
var stores the result andprint(random_ip)
displays it on the console.
By using the ipaddress
Module
The second approach is by utilizing another module namely, ipaddress
. It works in combination with random APIs and produces the IP address. Let’s watch how this technique works to generate a random IP address.
"""
IPv4 Address Generation using ipaddress module
"""
import ipaddress as ip
import random as rand
def gen_rand_ipv4():
return str(ip.IPv4Address(rand.randint(0, 2**32 - 1)))
ipv4_addr = gen_rand_ipv4()
print(f"Random IPv4 Address: {ipv4_addr}")
This example will also generate random IP addresses every time you run it.
Run#1 59.254.6.91
Run#2 147.85.134.87
Generating Random IPv6 Addresses
Now, we’ll again reuse the above techniques to generate random IPv6 addresses. However, the logic will be a little different to generate IPv6 blocks.
By using the random
Module
Here’s a script to generate random IPv6 addresses:
"""
IPv6 Address Generation using random module
"""
import random as rand
def gen_rand_ipv6():
"""Returns a random IPv6 addr."""
hextets = [hex(rand.randint(0, 65535))[2:].zfill(4) for _ in range(8)]
return ":".join(hextets)
# Example usage
random_ip = gen_rand_ipv6()
print(random_ip)
Below is the output of two runs of the above code.
Run#1 b8e7:a40f:1260:1645:62d5:0df9:34a1:44eb
Run#2 3ae5:4bc8:9db9:cf1c:fbbf:3c8a:a63c:cf09
Explanation:
- Similar structure: This code follows a similar structure to the IPv4 version but with adjustments for IPv6 specifics.
- Generate random
hextets
: The list comprehension[hex(random.randint(0, 65535))[2:].zfill(4) for _ in range(8)]
produces eight random integers between 0 and 65535. Each integer translates into a hexadecimal string by using the hex(). It is then sliced to remove the “0x” prefix using [2:]. The final string is left-padded with zeros by usingzfill(4)
to ensure a consistent length of four characters. These represent the eighthextets
(sections) of the IPv6 address. - Join
hextets
: Similar to IPv4, thejoin
() combines the eighthextets
with “.” as a separator into a single string, forming the complete IPv6 address.
By using the ipaddress
Module
Similarly, we can use the ipaddress
module to generate random IPv6 addresses. IPv6 addresses are more complex, so we need to use the IPv6Address
class.
"""
IPv6 Address Generation using ipaddress module
"""
import ipaddress as ip
import random as rand
def gen_rand_ipv6():
return str(ip.IPv6Address(rand.randint(0, 2**128 - 1)))
ipv6_addr = gen_rand_ipv6()
print(f"Random IPv6 Address: {ipv6_addr}")
Here, the gen_rand_ipv6
function generates a random IPv6 address using the IPv6Address
class. The range rand.randint(0, 2**128 - 1)
ensures that the generated integer is within the valid IPv6 address range. Below is the result from the two subsequent runs.
Run#1 46e6:a8a3:e36f:2382:9ad8:a5ae:705b:165
Run#2 aa08:bcc4:d7c2:4acf:a5c:ea19:9232:9fda
Generating IP Address By Versions
Our scripts currently generate both IPv4 and IPv6 addresses. However, sometimes we might need only one specific version. Here’s how to modify the functions:
"""
Version Specific IP Addr Generation
"""
import random as rand
def gen_rand_ipv4():
"""Generate a random IPv4 addr."""
octets = [str(rand.randint(0, 255)) for _ in range(4)]
return ".".join(octets)
def gen_rand_ipv6():
"""Generate a random IPv6 addr."""
hextets = [hex(rand.randint(0, 65535))[2:].zfill(4) for _ in range(8)]
return ":".join(hextets)
def gen_rand_ip(version=4):
"""Generate a random IP addr of a specific version (4 or 6)."""
if version == 4:
return gen_rand_ipv4()
elif version == 6:
return gen_rand_ipv6()
else:
raise ValueError("Invalid IP version. Please specify 4 or 6.")
# Example IPv4
random_ip = gen_rand_ip(version=4)
print(random_ip)
# Example IPv6
random_ip = gen_rand_ip(version=6)
print(random_ip)
Here is the output from the two runs of the above code:
Run#1 211.21.104.96
cff2:8887:ac42:6d8d:1cdc:d171:a0a7:33c6
Run#2 62.228.27.185
9a3c:a306:7eac:6dd8:86c2:482e:770c:4d13
Now, go through the details about the points that are the most important in the above code.
Explanation:
version
param: This param allows us to specify the desired IP version (4 or 6).- Conditional logic: The function checks the
version
param and calls the corresponding function (gen_rand_ipv4
orgen_rand_ipv6
) based on the value. - Error handling: The function raises a
ValueError
if an invalid version is provided.
Summary: Python’s Random IP Generation
In summary, learning how to create random IP addresses in Python is useful for practical tasks like testing networks, load testing, and web scraping. Using tools such as the ipaddress
module and third-party libraries like ipgetter
, you can simulate different scenarios effectively. These methods help with tasks such as checking network strength and making web scraping more anonymous. By adding these straightforward techniques to your Python scripts, you’ll be well-prepared for various challenges in network programming. So, try them out to improve your Python skills.
Happy coding!