basically I need the user to enter an ip address. All I need to do is check that it's valid (0-255; 4 octets). lets say a user enters 192.168.10.1, how can I break it down to 192, 168, 10, 1?
Asked
Active
Viewed 86 times
-4
-
1This can be solved via regular expressions. What have you tried so far? – BlackVegetable Feb 11 '16 at 19:53
-
1This can be solved trivially without regular expressions: `"192.168.0.1".split('.') == ['192', '168', '0', '1']` – Jon Surrell Feb 11 '16 at 19:57
-
1Check out [How to check if a string matches an IP adress pattern in python?](http://stackoverflow.com/q/3462784) – Bhargav Rao Feb 11 '16 at 20:01
-
If your problem is solved, you should accept the answer that helped the most. That gives a reward to the person who helped you and removes this question from the unanswered list. – zondo Apr 10 '16 at 03:43
5 Answers
3
Do this:
while True:
ip = raw_input("Please enter an ip address")
ip_split = ip.split(".")
if len(ip_split) != 4:
print "Must have 4 numbers"
elif not all(number.isdigit() for number in ip_split):
print "Must be numbers"
elif not all(0 <= int(number) <= 255 for number in ip_split):
print "Numbers must be in 0-255 range"
else:
ips = [int(number) for number in ip_split]
break

zondo
- 19,901
- 8
- 44
- 83
1
You can use the split
method:
your_string.split(separator)
In your case:
ip = "191.168.10.1"
values_list = ip.split(".")

Christian Tapia
- 33,620
- 7
- 56
- 73
0
I have this 2 regexes to check this
import re
ip4 = re.compile(r'^(?:(?:25[0-5]|2[0-4]\d|1\d\d|\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|\d?\d)$')
ip6 = re.compile(r'^(?:[\da-fA-F]{1,4}:){7}[\da-fA-F]{1,4}$')

Mr. E
- 2,070
- 11
- 23
0
You can do it in several ways. This could be a solution:
ip = "192.168.10.666"
octates = ip.split('.',4)
flag = True
for each_octate in octates:
num = int(each_octate)
if num>=0 and num<=255:
continue
else:
flag = False
break
if flag == True:
print "IP is correct!"
else:
print "IP is incorrect"

Jumayel
- 96
- 4
0
you can take the ip address in as a string and then from there split the str by "." and then check each member for that criteria.
ip = input("Enter Ip address: ")
address = ip.split('.')
if len(address) == 4:
for num in address:
if 255 >= num >= 0:
pass
else:
print("Invalid Ip Address!")
else:
print("Invalid Ip Address!")

Seekheart
- 1,135
- 7
- 8