Using a RegEx to match IP addresses in Python

Posted on

Question :

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

Asked By: MHibbin


Answer #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”

Answered By: DonCallisto

Answer #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
Answered By: Maria Zverina

Answer #3:

regex for ip v4:


otherwise you take not valid ip address like 999.999.999.999, etc

Answered By: burning_LEGION

Answer #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')
Answered By: Deepak

Answer #5:

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

Answered By: BlackVegetable

Answer #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')
Answered By: manju thimmareddy

Answer #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.

Answered By: Vaibhav Chaturvedi

Answer #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")
Answered By: Karthic Kannan

Leave a Reply

Your email address will not be published. Required fields are marked *