473,387 Members | 3,810 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

How to validate IP address in Python

Hi,

My programme has a text box where in user enters the ip address. I need to validate the IP (like no space allowed in the entry, the numerals should not exceed 255, not more than 3 dots allowed overall, no consecutive dots allowed etc.,.). How do i go about the same? Is there any built in function for the same?

thanks,
Badri
Nov 27 '06 #1
5 29141
bvdet
2,851 Expert Mod 2GB
Hi,

My programme has a text box where in user enters the ip address. I need to validate the IP (like no space allowed in the entry, the numerals should not exceed 255, not more than 3 dots allowed overall, no consecutive dots allowed etc.,.). How do i go about the same? Is there any built in function for the same?

thanks,
Badri
Badri,

This may cover most of of your requirements:
Expand|Select|Wrap|Line Numbers
  1. ip_str = "23.34.45.45"
  2.  
  3. def ipFormatChk(ip_str):
  4.     if len(ip_str.split()) == 1:
  5.         ipList = ip_str.split('.')
  6.         if len(ipList) == 4:
  7.             for i, item in enumerate(ipList):
  8.                 try:
  9.                     ipList[i] = int(item)
  10.                 except:
  11.                     return False
  12.                 if not isinstance(ipList[i], int):
  13.                     return False
  14.             if max(ipList) < 256:
  15.                 return True
  16.             else:
  17.                 return False
  18.         else:
  19.             return False
  20.     else:
  21.         return False
  22.  
  23. print ipFormatChk(ip_str)
  24. True
Nov 27 '06 #2
bartonc
6,596 Expert 4TB
Nice coding, BV!

Badri,

This may cover most of of your requirements:
Expand|Select|Wrap|Line Numbers
  1. ip_str = "23.34.45.45"
  2.  
  3. def ipFormatChk(ip_str):
  4.     if len(ip_str.split()) == 1:
  5.         ipList = ip_str.split('.')
  6.         if len(ipList) == 4:
  7.             for i, item in enumerate(ipList):
  8.                 try:
  9.                     ipList[i] = int(item)
  10.                 except:
  11.                     return False
  12.                 if not isinstance(ipList[i], int):
  13.                     return False
  14.             if max(ipList) < 256:
  15.                 return True
  16.             else:
  17.                 return False
  18.         else:
  19.             return False
  20.     else:
  21.         return False
  22.  
  23. print ipFormatChk(ip_str)
  24. True
Nov 27 '06 #3
You can also use regular expressions like this
Expand|Select|Wrap|Line Numbers
  1. import re
  2. ip_str = "23.34.45.45"
  3.  
  4. def ipFormatChk(ip_str):
  5.    pattern = r"\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"
  6.    if re.match(pattern, ip_str):
  7.       return True
  8.    else:
  9.       return False
  10. print ipFormatChk(ip_str)
  11.  
Dec 1 '06 #4
bvdet
2,851 Expert Mod 2GB
You can also use regular expressions like this
Expand|Select|Wrap|Line Numbers
  1. import re
  2. ip_str = "23.34.45.45"
  3.  
  4. def ipFormatChk(ip_str):
  5.    pattern = r"\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"
  6.    if re.match(pattern, ip_str):
  7.       return True
  8.    else:
  9.       return False
  10. print ipFormatChk(ip_str)
  11.  
Regular expressions are ideal for this application. This code executes much faster than the other. The drawback is readability. An alternative is to set the VERBOSE flag and add comments:
Expand|Select|Wrap|Line Numbers
  1. pattern = re.compile(r"""
  2.    \b                                           # matches the beginning of the string
  3.    (25[0-5]|                                    # matches the integer range 250-255 OR
  4.    2[0-4][0-9]|                                 # matches the integer range 200-249 OR
  5.    [01]?[0-9][0-9]?)                            # matches any other combination of 1-3 digits below 200
  6.    \.                                           # matches '.'
  7.    (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)       # repeat
  8.    \.                                           # matches '.'
  9.    (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)       # repeat
  10.    \.                                           # matches '.'
  11.    (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)       # repeat
  12.    \b                                           # matches the end of the string
  13.    """, re.VERBOSE)
It executes slower, but I guess you can't have everything! Thanks for posting Mike.
Dec 1 '06 #5
bartonc
6,596 Expert 4TB
Regular expressions are ideal for this application. This code executes much faster than the other. The drawback is readability. An alternative is to set the VERBOSE flag and add comments:
Expand|Select|Wrap|Line Numbers
  1. pattern = re.compile(r"""
  2.    \b                                           # matches the beginning of the string
  3.    (25[0-5]|                                    # matches the integer range 250-255 OR
  4.    2[0-4][0-9]|                                 # matches the integer range 200-249 OR
  5.    [01]?[0-9][0-9]?)                            # matches any other combination of 1-3 digits below 200
  6.    \.                                           # matches '.'
  7.    (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)       # repeat
  8.    \.                                           # matches '.'
  9.    (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)       # repeat
  10.    \.                                           # matches '.'
  11.    (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)       # repeat
  12.    \b                                           # matches the end of the string
  13.    """, re.VERBOSE)
It executes slower, but I guess you can't have everything! Thanks for posting Mike.
I like you style, BV.
Dec 1 '06 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

10
by: michaaal | last post by:
I realize this is not solely an ASP question, but I thought you guys might know the answer and I couldn't find anywhere else to post this. If you have suggestions for this I am more than happy to...
12
by: Dag Sunde | last post by:
My understanding of regular expressions is rudimentary, at best. I have this RegExp to to a very simple validation of an email-address, but it turns out that it refuses to accept mail-addresses...
6
by: Tony Nelson | last post by:
I'd like to have a fast way to validate large amounts of string data as being UTF-8. I don't see a fast way to do it in Python, though: unicode(s,'utf-8').encode('utf-8) seems to notice at...
5
by: Dave | last post by:
Hello. Is there any method to validate if string contains valid IP address? I also need the method to valideta email address in string. Thank you.
3
by: Wm. Scott Miller | last post by:
Hello all: I'd like some advice on the best way to validate and confirm an e-mail address entered during a registration process. What we are thinking of is something like the following: 1. ...
2
by: Reid Priedhorsky | last post by:
Hi folks, I have a need to validate XML files against both DTDs and XML Schema from the command line. In an ideal world, I'd be able to do something like: $ python validate.py foo.xml ...
23
by: codefire | last post by:
Hi, I am trying to get a regexp to validate email addresses but can't get it quite right. The problem is I can't quite find the regexp to deal with ignoring the case james..kirk@fred.com, which...
1
by: SkipNRun | last post by:
I am a novice when comes to JavaScript, AJAX. I am working on a form, which will allow users to update their contact information. In order to make the form flexible, I need to use pull down list. ...
1
by: saravanatmm | last post by:
I need javascript code for validate the email address. Email address field cannot allowed the capital letters, special characters except '@' symbol. But can allowed the small letters, numeric...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.