Check if valid ip address from user input
You can use ipaddress
module.
For example:
import ipaddress
while True:
try:
a = ipaddress.ip_address(input('Enter IP address: '))
break
except ValueError:
continue
print(a)
Prints (for example):
Enter IP address: s
Enter IP address: a
Enter IP address: 1.1.1.1
1.1.1.1
check if a string matches an IP address pattern in python?
update: The original answer bellow is good for 2011, but since 2012, one is likely better using Python's ipaddress stdlib module - besides checking IP validity for IPv4 and IPv6, it can do a lot of other things as well.</update>
It looks like you are trying to validate IP addresses. A regular expression is probably not the best tool for this.
If you want to accept all valid IP addresses (including some addresses that you probably didn't even know were valid) then you can use IPy (Source):
from IPy import IP
IP('127.0.0.1')
If the IP address is invalid it will throw an exception.
Or you could use socket
(Source):
import socket
try:
socket.inet_aton(addr)
# legal
except socket.error:
# Not legal
If you really want to only match IPv4 with 4 decimal parts then you can split on dot and test that each part is an integer between 0 and 255.
def validate_ip(s):
a = s.split('.')
if len(a) != 4:
return False
for x in a:
if not x.isdigit():
return False
i = int(x)
if i < 0 or i > 255:
return False
return True
Note that your regular expression doesn't do this extra check. It would accept 999.999.999.999
as a valid address.
Validate IP Address
The type of sublist[nos]
is <class 'str'>
, not <class 'int'>
.
So, you should change the validnos
to next to fix it:
validnos=['0','1','2','3','4','5','6','7','8','9']
validating if a user entered an ip address or CIDR notation when prompted
The ipaddress
class does not appear to provide any convenience methods for determinig whether a string represents a valid IPv4 address versus a valid IPv4 network versus neither a valid address or network.
However, you can build your own rudimentary functionality to check to see if one or the other throws an exception and return true
or false
and use it in your conditional:
import ipaddress
def valid_ip_or_cidr(ip):
try:
ipaddress.IPv4Address(ip)
print('valid as address')
return True
except:
try:
ipaddress.IPv4Network(ip)
print('valid as network')
return True
except:
print('invalid as both an address and network')
return False
valid_ip_or_cidr('192.168.1.1')
# valid as address
# True
valid_ip_or_cidr('192.168.1.0/24')
# valid as network
# True
valid_ip_or_cidr('foo')
# invalid as both an address and network
# False
In your context, this would be implemented in your conditional as:
newIpAddress = input("Please enter the IP address for SFTP access: ")
if valid_ip_or_cidr(newIpAddress):
# code to execute if validation succeeds
How to validate IP address using Robot Framework
Builtin library has a keyword for matching regexes. You can use Should Match Regexp to validate the ip. Here is an example I made with a regexp from this answer
***Variables***
${correct_ip} 192.168.101.12
${false_ip} 999.999.999.999
${ip_regexp} ^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$
*** Test Cases ***
test
Should Match Regexp ${correct_ip} ${ip_regexp}
Should Not Match Regexp ${false_ip} ${ip_regexp}
ip address validation in python using regex
Use anchors instead:
aa=re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$",ip)
These make sure that the start and end of the string are matched at the start and end of the regex. (well, technically, you don't need the starting ^
anchor because it's implicit in the .match()
method).
Then, check if the regex did in fact match before trying to access its results:
if aa:
ip = aa.group()
Of course, this is not a good approach for validating IP addresses (check out gnibbler's answer for a proper method). However, regexes can be useful for detecting IP addresses in a larger string:
ip_candidates = re.findall(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b", ip)
Here, the \b
word boundary anchors make sure that the digits don't exceed 3 for each segment.
validate the IP address from the given list in Python
I didn't recreate your functions, but I put this together for you. The code below can easily be added to a function (e.g. ip_address_validation).
# Python module for Regular expressions
import re
# Valid IPv4 address format
IPv4_format = '(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])'
# Valid IPv6 address format
IPv6_format = '(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,' \
'2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))'
possible_IP_addresses = ['100.243.537.591', 'HBA.KJFH.LSHF', '172.16.254.1', '2001:0db8:85a3:0:0:8A2E:0370:7334', '256.256.256.256']
for address in possible_IP_addresses:
is_IPv4 = re.compile(r'{}'.format(IPv4_format))
match_IPv4 = re.match(is_IPv4, address)
is_IPv6 = re.compile(r'{}'.format(IPv6_format))
match_IPv6 = re.match(is_IPv6, address)
if match_IPv4:
print ('Valid IPv4 address: {}'.format(address))
# output
Valid IPv4 address: 172.16.254.1
elif match_IPv6:
print ('Valid IPv6 address: {}'.format(address))
# output
Valid IPv6 address: 2001:0db8:85a3:0:0:8A2E:0370:7334
else:
print ('Not a valid IPv4 or IPv6 address: {}'.format(address))
# output
Not a valid IPv4 or IPv6 address: 100.243.537.591
Not a valid IPv4 or IPv6 address: HBA.KJFH.LSHF
Not a valid IPv4 or IPv6 address: 256.256.256.256
validating IP address - python
>>> import socket
>>> socket.inet_aton("127.0.0.1") # valid
'\x7f\x00\x00\x01'
>>> socket.inet_aton("127.1") # oh yes this is valid too!
'\x7f\x00\x00\x01'
>>> socket.inet_aton("127.0.0,1") # this isn't
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
socket.error: illegal IP address string passed to inet_aton
to test for valid IPv6 addresses you can use
>>> socket.inet_pton(socket.AF_INET6, "2001:db8:1234::")
b' \x01\r\xb8\x124\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
Related Topics
How to Get Href Links from HTML Using Python
How to Install and Import Python Modules at Runtime
Financial Charts/Graphs in Ruby or Python
In Matplotlib, What Does the Argument Mean in Fig.Add_Subplot(111)
Python Selenium Click on Button
Get Md5 Hash of Big Files in Python
Polling the Keyboard (Detect a Keypress) in Python
How to Mock an Open Used in a with Statement (Using the Mock Framework in Python)
Why Are Packages Installed Rather Than Just Linked to a Specific Environment
Creating a Dynamic Choice Field
Beautifulsoup Webscraping Find_All( ): Finding Exact Match
How to Build 32Bit Python 2.6 on 64Bit Linux
Is There a Python Equivalent to Ruby Symbols
How to Construct a Timedelta Object from a Simple String
Python Script to Do Something at the Same Time Every Day
Grouping Python Dictionary Keys as a List and Create a New Dictionary with This List as a Value