Last modified: September 09, 2021

Python: 3 methods to check if a string is a valid IP address


In this article, we're going to learn how to check if a string is a valid IP address using 4 methods:

Check if String is a valid IP using Iptools

Iptools is a library for dealing with IP addresses.

We can use the iptools library to validate IP Adresse, but first, let's install the library.

Installation via pip:

pip install iptools

Syntax:


iptools.ipv4.validate_ip(ip)

Returns True if IP is validate, False otherwise.


Let's see an example:


import iptools

ip = '127.0.0.1'

c_ip = iptools.ipv4.validate_ip(ip)

if c_ip is True:
    print("Valid")

else:
    print("Invalid")

Output:

Valid

Check if String is a valid IP using IPy

IPy is a library for handling IPv4 and IPv6 addresses and networks.

Installation via pip:

pip install IPy

Let's see how to use it.

Syntax:

IP(ip)

If IP is validated, the program will continue if not will return ValueError.

Let's try on invalid Ip address:


from IPy import IP

ip = "127.0.0.2.5"

IP(ip)

print('Valid')

Output:

Traceback (most recent call last):
  File "test.py", line 18, in <module>
    IP(ip)
  File "/home/py/.local/lib/python3.8/site-packages/IPy.py", line 249, in __init__
    (self.ip, parsedVersion) = parseAddress(ip, ipversion)
  File "/home/py/.local/lib/python3.8/site-packages/IPy.py", line 1439, in parseAddress
    raise ValueError("IP Address format was invalid: %s" % ipstr)
ValueError: IP Address format was invalid: 

We'll use Try and except to handle ValueError.


from IPy import IP

ip = "127.0.0.2.5"

try:
    IP(ip)
    print('Valid')
except:
    print("Invalid")

Output:

Invalid

Check if String is a valid IP using Socket

We can also use Socket to check if a string is a valid IP Adresse.

Example:


import socket

ip = "127.0.0.1"

try:
    socket.inet_aton(ip)
    print('Valid')
except socket.error:
    print("Invalid")

Output:

Valid