[Solved] 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"
   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+.

Enquirer: MHibbin


Solution #1:

You have to modify your regex in the following way

pat = re.compile("^d{1,3}.d{1,3}.d{1,3}.d{1,3}$")

that’s because . is a wildcard that stands for “every character”

Respondent: DonCallisto

Solution #2:

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):
        return True
        return False

print valid_ip('')
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):
        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
        return False
Respondent: Maria Zverina

Solution #3:

regex for ip v4:


otherwise you take not valid ip address like 999.999.999.999, etc

Respondent: burning_LEGION

Solution #4:

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):
        print ipaddress.ip_address(address)
        return True
        return False

print valid_ip('')
print valid_ip('2001:DB8::1')
print valid_ip('gibberish')
Respondent: Deepak

Solution #5:

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

Respondent: BlackVegetable

Solution #6:

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
            flag = 0
if (flag == 4):
    print("valid ip")
    print('No match for ip or not a valid ip')
Respondent: manju thimmareddy

Solution #7:

import re
ipv=raw_input("Enter an ip address")
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.

Solution #8:

str = ""

list1 = str.split('.')


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

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

Solution #9:

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
                    for ipAddr in ipFound:
                        for byte in ipAddr:
                            if int(byte) not in range(1, 255):
                                hasIncorrectBytes = True
                    if not hasIncorrectBytes:
                hasIncorrectBytes = True

    return ips
Respondent: Unguest

Solution #10:

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 ("=====================")
        else :
            print ("nInvalid IP")
    else :
        print ("nAllowed Max 5 times")

Reply me if you have doubt?

Solution #11:

import re

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

Here my valid IP Address is only and assuming is not a valid one as it is combined with some string and 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 =,st1)


================ RESTART: C:/Python27/Srujan/ ================ 

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' ''.

Please comment if any modifications are required.

Respondent: srujan kumar

Solution #12:

This works for python 2.7:

import re
a=raw_input("Enter a valid IP_Address:")
if re.match(b,a) and b<255:
    print "Valid"
    print "invalid"
Respondent: Rajeev Sharma

Solution #13:

“”” 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)', '')

if IPV4:
    print ("Valid IP address")

    print("Invalid IP address")
Respondent: ROHIT RAI

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy