Python is a universal language that is used in many fields. One of these fields is networking where you will have to work with IP addresses more. As you are using Python to handle your networking tasks, you might want to validate IP addresses or maybe search IP addresses. Python’s regular expressions (regex) provide a powerful way to match and manipulate IP addresses.
In this tutorial, you will learn how you can use Python regex to work with IP addresses.
Here is what you will learn:
- Understanding an IP address
- Matching an IP address
- Defining the Pattern
- An Example
- Validating an IP address
- Extracting an IP address
- Conclusion
Understanding an IP address
Before we dive deep into working with IP addresses we should get to understand what they are and their format. An IP address is simply a numerical identifier assigned to each device connected to a computer network. It stands for Internet Protocol address. It acts as an identification for devices, enabling network communication between them. The format of an IP address is as follows, we have four sets of integers, separated by dots, such as 192.168.0.1. Each set is capable of having a value between 0 and 255.
Matching an IP address
As you are working with IP addresses you will likely encounter a scenario where you are required to match an IP address. With Python regex, this is not a complex task, you use the re.match()
method.
Defining the Pattern
If you want to match an IP address, you will need first of all to define a pattern. A pattern for matching an IP address is as follows:
^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$
Here is what the pattern means:
^
and$
represent the start and end of the string, respectively, ensuring that the entire string matches the pattern.\d{1,3}
matches one to three digits, allowing values from 0 to 255.\.
matches the dot separator between each set of numbers.
An Example
Now that you know the pattern for matching an IP address, let us look at an example for a better understanding:
import re
# the IP address to match
ip_address = "172.67.173.18"
# regex pattern for matching IP addresses
pattern = r'^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$'
# match the IP address against the pattern
match = re.match(pattern, ip_address)
# check if the match is successful
if match:
print("Valid IP address")
else:
print("Invalid IP address")
Here’s a breakdown of the code:
- The IP address to match is stored in the
ip_address
variable. - The regex pattern for matching IP addresses is defined using the r prefix to create a raw string. The pattern uses groups and
\d
to match digits. Each group is enclosed in parentheses( )
. - The
re.match()
function is used to perform the matching operation. It takes the pattern and the string to match as arguments. - If a match is found, the
match
variable will contain a match object. We check ifmatch
is True to determine if the IP address is valid or not.
Output:
#Output
Valid IP address
Validating an IP address
Another practical example, when you are working with IP addresses, is validating it. Here is an example of validating an IP address:
import re
def validate_ip_address(ip_address):
# regex pattern for validating IP address
pattern = r'^(\d{1,3}\.){3}\d{1,3}$'
# perform a match using the pattern on the given IP address
match = re.match(pattern, ip_address)
# if there is a match, return True; otherwise, return False
return bool(match)
# test the function with an example IP address
ip_address = "172.67.173.18"
if validate_ip_address(ip_address):
print("Valid IP address")
else:
print("Invalid IP address")
The code defines a regular expression pattern pattern
that matches the format of an IP address. The re.match()
method is used to check if the ip_address
matches the pattern
. If there is a match, the method returns True
, indicating a valid IP address. Otherwise, it returns False
. The provided IP address is tested using the validate_ip_address
function.
Extracting an IP address
It is so likely that you will encounter a scenario where you would like to extract an IP address from some text. For this task, you will have to use the re.findall()
method. Here is an example:
import re
# example text containing IP addresses
text = "This is a sample text with IP addresses like 192.168.0.1, 172.67.173.18 and 10.0.0.2"
# regex pattern for matching IP addresses
pattern = r'\b(?:\d{1,3}\.){3}\d{1,3}\b'
# find all occurrences of IP addresses in the text
ip_addresses = re.findall(pattern, text)
# print the extracted IP addresses
for ip_address in ip_addresses:
print(ip_address)
In the code snippet, we define a text containing multiple IP addresses separated by commas. Then we define a regex pattern r'\b(?:\d{1,3}\.){3}\d{1,3}\b'
to match IP addresses. Let’s break down the pattern:
\b
is a word boundary to ensure that we match complete IP addresses.(?:\d{1,3}\.){3}
matches three occurrences of1
to3
digits followed by a dot. This captures the first three segments of the IP address.\d{1,3}
matches the final segment of the IP address, which can have1
to3
digits.
We use the re.findall()
method to find all occurrences of the IP addresses in the text based on the pattern. The results are stored in the ip_addresses
list.
Finally, we iterate over the ip_addresses
list and print each extracted IP address.
Output:
#Output
192.168.0.1
172.67.173.18
10.0.0.2
Conclusion
That concludes this tutorial. This tutorial has walked you through some important skills you can use when working with IP addresses in your networking tasks. We hope that the skills gained will be useful in your networking tasks.