Python Forum
IP address validation
Thread Rating:
  • 1 Vote(s) - 3 Average
  • 1
  • 2
  • 3
  • 4
  • 5
IP address validation
#1
Hello guys,
In this program i need to check whether the given ip is valid or not?
print "Enter the IP:"
save=raw_input()
regex="^(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$"

if save in regex:
     print "Valid ip"
else:
     print "invalid ip"
i got nothing as my output
What is the mistake here?
Reply
#2
I'm not sure why you're not getting output. How are you running it?

When I run it, it is going to give "invalid ip" for all valid IP addresses. That's because you're using the regex wrong. You can't just use the 'in' operator for a regex, that just tests if one basic string is in another basic string. To use regular expressions in Python, you need to import the re module, compile the regex with the re.compile() function, and then pass the IP address to the search method of the compiled regular expression. (There are other ways to use the re module, but that's the way I do it.)
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
I don't have Python 2, but using the forums ">Code" button (see top row of buttons) I get the following:

Enter the IP:
192.168.10.2    # a valid IP

Invalid ip
If I enter no IP (just hit enter) I get:

Enter the IP:

Valid ip
So not sure what you mean by "i got nothing as my output"
If it ain't broke, I just haven't gotten to it yet.
OS: Windows 10, openSuse 42.3, freeBSD 11, Raspian "Stretch"
Python 3.6.5, IDE: PyCharm 2018 Community Edition
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020