473,404 Members | 2,213 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,404 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 29143
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: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.