How do I check if a value is a valid IP address in Python?
Alex K
alex k profile pic

To check if a value is a valid IP address in Python, you can use theipaddress module, which provides classes for representing and manipulating IP addresses and networks. Here's a detailed explanation of how to accomplish this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

import ipaddress

def is_valid_ip(address):
    try:
   ipaddress.ip_address(address)
   return True
    except ValueError:
   return False

ip = "192.168.0.1"

if is_valid_ip(ip):
    print("The IP address is valid.")
else:
    print("The IP address is not valid.")

In this example, theis_valid_ip() function checks if the providedaddress is a valid IP address by attempting to create anip_address object usingipaddress.ip_address(address). If the value is a valid IP address, the function returnsTrue; otherwise, it returnsFalse when aValueError is raised. Theipaddress.ip_address() method validates both IPv4 and IPv6 addresses. If the provided address is a valid IP address, it will be accepted. Note: This method validates the IP address structure but does not guarantee that the IP address is reachable or active on the network. Alternatively, if you only want to check if the address is a valid IPv4 address, you can use theipaddress.IPv4Address class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

import ipaddress

def is_valid_ipv4(address):
    try:
   ipaddress.IPv4Address(address)
   return True
    except ValueError:
   return False

ip = "192.168.0.1"

if is_valid_ipv4(ip):
    print("The IPv4 address is valid.")
else:
    print("The IPv4 address is not valid.")

In this case, theis_valid_ipv4() function uses theIPv4Address class to validate IPv4 addresses specifically. Summary: To check if a value is a valid IP address in Python, you can use theipaddress module. By attempting to create anip_address orIPv4Address object with the provided value, you can determine if it is a valid IP address. This method helps ensure the correctness and validity of IP addresses within your Python code.