[python] Using a RegEx to match IP addresses in Python

I'm trying to make a test for checking whether a sys.argv input matches the RegEx for an IP address...

As a simple test, I have the following...

import re

pat = re.compile("\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}")
test = pat.match(hostIP)
if test:
   print "Acceptable ip address"
else:
   print "Unacceptable ip address"

However when I pass random values into it, it returns "Acceptable IP address" in most cases, except when I have an "address" that is basically equivalent to \d+.

This question is related to python regex

The answer is


I came across the same situation, I found the answer with use of socket library helpful but it doesn't provide support for ipv6 addresses. Found a better way for it:

Unfortunately it Works for python3 only

import ipaddress

def valid_ip(address):
    try: 
        print ipaddress.ip_address(address)
        return True
    except:
        return False

print valid_ip('10.10.20.30')
print valid_ip('2001:DB8::1')
print valid_ip('gibberish')

If you really want to use RegExs, the following code may filter the non-valid ip addresses in a file, no matter the organiqation of the file, one or more per line, even if there are more text (concept itself of RegExs) :

def getIps(filename):
    ips = []
    with open(filename) as file:
        for line in file:
            ipFound = re.compile("^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$").findall(line)
            hasIncorrectBytes = False
            try:
                    for ipAddr in ipFound:
                        for byte in ipAddr:
                            if int(byte) not in range(1, 255):
                                hasIncorrectBytes = True
                                break
                            else:
                                pass
                    if not hasIncorrectBytes:
                        ips.append(ipAddr)
            except:
                hasIncorrectBytes = True

    return ips

regex for ip v4:

^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$

otherwise you take not valid ip address like 999.999.999.999, 256.0.0.0 etc


IP address uses following authentication :

  1. 255 ---> 250-255
  2. 249 ---> 200-249
  3. 199 ---> 100-199
  4. 99 ---> 10-99
  5. 9 ---> 1-9

    import re    
    k = 0
    while k < 5 : 
        i = input("\nEnter Ip address : ")
        ip = re.match("^([1][0-9][0-9].|^[2][5][0-5].|^[2][0-4][0-9].|^[1][0-9][0-9].|^[0-9][0-9].|^[0-9].)([1][0-9][0-9].|[2][5][0-5].|[2][0-4][0-9].|[1][0-9][0-9].|[0-9][0-9].|[0-9].)([1][0-9][0-9].|[2][5][0-5].|[2][0-4][0-9].|[1][0-9][0-9].|[0-9][0-9].|[0-9].)([1][0-9][0-9]|[2][5][0-5]|[2][0-4][0-9]|[1][0-9][0-9]|[0-9][0-9]|[0-9])$",i)
        k = k + 1 
        if ip:
            print ("\n=====================")
            print ("Valid IP address")
            print ("=====================")
            break
        else :
            print ("\nInvalid IP")
    else :
        print ("\nAllowed Max 5 times")
    

Reply me if you have doubt?


str = "255.255.255.255"
print(str.split('.'))

list1 = str.split('.')

condition=0

if len(list1)==4:
    for i in list1:
        if int(i)>=0 and int(i)<=255:
            condition=condition+1

if condition!=4:
    print("Given number is not IP address")
else:
    print("Given number is valid IP address")

""" regex for finding valid ip address """

import re


IPV4 = re.fullmatch('([0-2][0-5]{2}|\d{2}|\d).([0-2][0-5]{2}|\d{2}|\d).([0-2][0-5]{2}|\d{2}|\d).([0-2][0-5]{2}|\d{2}|\d)', '100.1.1.2')

if IPV4:
    print ("Valid IP address")

else:
    print("Invalid IP address")

This works for python 2.7:

import re
a=raw_input("Enter a valid IP_Address:")
b=("[0-9]+"+".")+"{3}"
if re.match(b,a) and b<255:
    print "Valid"
else:
    print "invalid"

import re
ipv=raw_input("Enter an ip address")
a=ipv.split('.')
s=str(bin(int(a[0]))+bin(int(a[1]))+bin(int(a[2]))+bin(int(a[3])))
s=s.replace("0b",".")
m=re.search('\.[0,1]{1,8}\.[0,1]{1,8}\.[0,1]{1,8}\.[0,1]{1,8}$',s)
if m is not None:
    print "Valid sequence of input"
else :
    print "Invalid input sequence"

Just to keep it simple I have used this approach. Simple as in to explain how really ipv4 address is evaluated. Checking whether its a binary number is although not required. Hope you like this.


You are trying to use . as a . not as the wildcard for any character. Use \. instead to indicate a period.


Using regex to validate IP address is a bad idea - this will pass 999.999.999.999 as valid. Try this approach using socket instead - much better validation and just as easy, if not easier to do.

import socket

def valid_ip(address):
    try: 
        socket.inet_aton(address)
        return True
    except:
        return False

print valid_ip('10.10.20.30')
print valid_ip('999.10.20.30')
print valid_ip('gibberish')

If you really want to use parse-the-host approach instead, this code will do it exactly:

def valid_ip(address):
    try:
        host_bytes = address.split('.')
        valid = [int(b) for b in host_bytes]
        valid = [b for b in valid if b >= 0 and b<=255]
        return len(host_bytes) == 4 and len(valid) == 4
    except:
        return False

def ipcheck():
# 1.Validate the ip adderess
input_ip = input('Enter the ip:')
flag = 0

pattern = "^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$"
match = re.match(pattern, input_ip)
if (match):
    field = input_ip.split(".")
    for i in range(0, len(field)):
        if (int(field[i]) < 256):
            flag += 1
        else:
            flag = 0
if (flag == 4):
    print("valid ip")
else:
    print('No match for ip or not a valid ip')

import re

st1 = 'This is my IP Address10.123.56.25 789.356.441.561 127 255 123.55 192.168.1.2.3 192.168.2.2 str1'

Here my valid IP Address is only 192.168.2.2 and assuming 10.123.56.25 is not a valid one as it is combined with some string and 192.168.1.2.3 not valid.

pat = r'\s(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\.){3}((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\s|$))'

match = re.search(pat,st1)

print match.group()

================ RESTART: C:/Python27/Srujan/re_practice.py ================
192.168.2.2 

This will grep the exact IP Address, we can ignore any pattern look like an IP Address but not a valid one. Ex: 'Address10.123.56.25', '789.356.441.561' '192.168.1.2.3'.

Please comment if any modifications are required.