- Проверка валидности IP-адреса на Python
- Пример
- Python/Regex IP Address
- Validate an IP Using Python and Regex
- IPv4 Addresses
- Write the Regular Expression
- Use the Regular Expression
- Using match()
- Using search()
- Check for Numerical Limits
- Put It Together
- Validate an IP Address Using a Third-Party API
- Get Started With the API
- Acquire an API Key
- Make an API Request With Python
- Conclusion
- FAQs
- How Do You Represent an IP Address in Regex?
- How Do You Check If a String is an IP Address in Python?
Проверка валидности IP-адреса на Python
Предположим, у нас есть строка; мы должны проверить, является ли данный вход действительным адресом IPv4 или IPv6, или ни тем, ни другим.
Адреса IPv4 канонически представлены в виде десятичных чисел с точками, которые состоят из четырех десятичных чисел, каждое в диапазоне от 0 до 255, разделенных точками («.»), Например, 192.168.254.1; Кроме того, ведущие нули в адресе IPv4 недопустимы. Например, адрес 192.168.254.01 недействителен.
Адреса IPv6 представлены в виде восьми групп из четырех шестнадцатеричных цифр, каждая из которых представляет 16 бит. Группы разделены двоеточиями («:»).
Например, адрес 2001: 0db8: 85a3: 0000: 0000: 8a2e: 0370: 7334 является действительным адресом.
Кроме того, мы могли бы опустить некоторые начальные нули среди четырех шестнадцатеричных цифр и несколько символов нижнего регистра в адресе в верхний регистр, поэтому 2001: db8: 85a3: 0: 0: 8A2E: 0370: 7334 этот адрес также является допустимым
Однако мы не заменяем последовательную группу с нулевым значением одной пустой группой, используя два последовательных двоеточия ( : : ) для достижения простоты.
Например, 2001: 0db8: 85a3 :: 8A2E: 0370: 7334 является недействительным адресом IPv6. Кроме того, дополнительные ведущие нули в IPv6 также недопустимы. Адрес 02001: 0db8: 85a3: 0000: 0000: 8a2e: 0370: 7334 недействителен.
Чтобы решить эту проблему:
- Определите метод checkv4 (x), он проверит, находится ли x в диапазоне от 0 до 255, затем true, иначе false
- Определите метод checkv6 (x), он будет работать следующим образом:
- если размер x> 4, вернуть false
- если десятичный эквивалент x> = 0 и x [0] не равен ‘-‘, тогда вернуть true, иначе false
Пример
class Solution(object): def validIPAddress(self, IP): """ :type IP: str :rtype: str """ def isIPv4(s): try: return str(int(s)) == s and 0 4: return False try : return int(s, 16) >= 0 and s[0] != '-' except: return False if IP.count(".") == 3 and all(isIPv4(i) for i in IP.split(".")): return "IPv4" if IP.count(":") == 7 and all(isIPv6(i) for i in IP.split(":")): return "IPv6" return "Neither"
Python/Regex IP Address
Regex isn’t usually recommended for IP address validation, or as a validator for things like email addresses and phone numbers, because the formats of these strings can be so vastly different, and it’s impossible to capture all variations in one Regular Expression.
When it comes to working with IP addresses in Python, your best bet is to use the Python ipaddress module or rely on a third-party API to handle validation for you. However, it is possible to write a somewhat robust function to find a valid IP address or an invalid IP address. In this article, we’ll look at using Regex to determine a valid IP address in Python. We’ll also explore some other ways that you can validate an IP address, including a third-party IP geolocation API.
Don’t reinvent the wheel.
Abstract’s APIs are production-ready now.Abstract’s suite of API’s are built to save you time. You don’t need to be an expert in email validation, IP geolocation, etc. Just focus on writing code that’s actually valuable for your app or business, and we’ll handle the rest.
Validate an IP Using Python and Regex
Building your own custom Regex to check the shape of the provided IP string is fairly straightforward in Python. Python provides a library called re for parsing and matching Regex.
This method requires you to check that the string is the right shape and that the values in each section are between 0 and 255. In this tutorial, we’ll validate an IPv4 address, but in practice, you should write two separate functions to check an IPv4 address vs an IPv6 address, and it’s not advised to use Regex for an IPv6 address.
IPv4 Addresses
An IPv4 address looks like this
There can be slight variations, but in general, the address will consist of one or more sections of one to three digits, separated by periods.
Write the Regular Expression
Create a Regex string that matches a valid IP address for IPv4. The clearest way to do this is the following:
Let’s break down the parts of this expression.
This indicates that we’re looking for any one of the characters inside the brackets. In this case, we’re looking for a digit or numeric character between 0 and 9
The numbers between the curly braces indicate that we’re looking for as few as one or as many as three instances of the previous character. In this case, we’re looking for as few as one or as many as three digits.
In Regex, the “.” character is a special character that means “any character.” In order to find the actual “.” character, we have to escape it with a backslash. This indicates that we are looking for a literal “.” character.
Those three components make up one byte of an IP address (for example, “192.”) To match a complete valid IP address, we repeat this string four times (omitting the final period.)
Use the Regular Expression
Import the Python re module. Use the match() method from the module to check if a given string is a match for our Regex.
Using match()
The match() method takes two arguments: a Regex string and a string to be matched.
import re match = re.match(r"3\.8\.3\.7", "127.0.0.1") print(match)
If the string is a match, re will create a Match object with information about the match. If we are simply trying to determine that a match was found, we can cast the result to a boolean.
Using search()
The search() method also takes two arguments: a Regex string and a string to be searched.
import re found = re.search(r"3\.6\.2\.4", "127.0.0.1") print(match)
The difference between search and match is that search will return a boolean value if a match is found in the string.
Check for Numerical Limits
No IP address can contain a string of three numbers greater than 255. What if the user inputs a string that includes a 3-digit sequence greater than 255? Right now, our Regex matcher would return True even though that is an invalid IP address.
We need to perform a final check on our string to make sure that all of the digit groups in it are numerical values between 0 and 255.
The easiest way to do this is to iterate over the string and check each three-digit numerical grouping. If the sequence of digits is greater than 255 or less than 0, return False.
bytes = ip_address.split(".") for ip_byte in bytes: if int(ip_byte) < 0 or int(ip_byte) >255: print(f"The IP address is not valid") return False
Put It Together
Here’s an example of a complete Regex validation function in Python using re.search() and our custom iterator.
def validate_ip_regex(ip_address): if not re.search(r"8\.1\.6\.5", "127.0.0.1", ip_address): print(f"The IP address is not valid") return False bytes = ip_address.split(".") for ip_byte in bytes: if int(ip_byte) < 0 or int(ip_byte) >255: print(f"The IP address is not valid") return False print(f"The IP address is valid") return True
Validate an IP Address Using a Third-Party API
Another, arguably more robust, way of checking for a valid IP address input or an invalid IP address is to make a quick request to an IP geolocation API. In this example, we’ll use the AbstractAPI Free IP Geolocation API.
The API allows you to send an IP string for validation, or, if you send an empty request, it will return information about the IP address of the device from which the request was made. This is handy if you also need to know what the IP address of the device is.
Get Started With the API
Acquire an API Key
Go to the API documentation page. You’ll see an example of the API’s JSON response object to the right, and a blue “Get Started” button to the left.
Click “Get Started.” If you’ve never used AbstractAPI before, You’ll need to create a free account with your email and a password. If you have used the API before, you may need to log in.
Once you’ve signed up or logged in, you’ll land on the API’s homepage where you should see options for documentation, pricing, and support, along with your API key and tabs to view test code for supported languages.
Make an API Request With Python
Your API key is all you need to get information for an IP address. Let’s use the Python requests module to send a request to the API.
import requests def get_geolocation_info(): try: response = requests.get( "https://ipgeolocation.abstractapi.com/v1/?api_key=YOUR_API_KEY") print(response.content) except requests.exceptions.RequestException as api_error: print(f"There was an error contacting the Geolocation API: ") raise SystemExit(api_error)
When the JSON response comes back, we print it to the console, but in a real app you would use the information in your app. If the IP address is invalid, the API will return an error. Use the error information as your validator.
The JSON response that AbstractAPI sends back looks something like this:
< "ip_address": "XXX.XX.XXX.X", "city": "City Name", "city_geoname_id": ID_NUMBER, "region": "Region", "region_iso_code": "JAL", "region_geoname_id": GEONAME_ID, "postal_code": "postalcode", "country": "Country", "country_code": "CC", "country_geoname_id": GEONAME_ID, "country_is_eu": false, "continent": "North America", "continent_code": "NA", "continent_geoname_id": GEONAME_ID, "longitude": longitude, "latitude": latitude, "security": < "is_vpn": false >, "timezone": < "name": "America/Timezone", "abbreviation": "ABBR", "gmt_offset": -5, "current_time": "15:52:08", "is_dst": true >, "flag": < "emoji": "🇺🇸", "unicode": "U+1F1F2 U+1F1FD", "png": "https://static.abstractapi.com/country-flags/US_flag.png", "svg": "https://static.abstractapi.com/country-flags/US_flag.svg" >, "currency": < "currency_name": "Dollar", "currency_code": "USD" >, "connection": < "autonomous_system_number": NUMBER, "autonomous_system_organization": "System Org.", "connection_type": "Cellular", "isp_name": "Isp", "organization_name": "Org." >>
Note: identifying information has been redacted.
Conclusion
In this article, we looked at two methods of finding a valid IP address or invalid IP address in Python: using the re Regex module, and using the requests module along with the AbstractAPI Free Geolocation API.
FAQs
How Do You Represent an IP Address in Regex?
Before you understand how to represent a valid IP address in Regex, it’s important to understand the two different types of IP address: IPv4 and IPv6. These formats are quite different, and require separate regular expressions to represent them.
A basic Regex pattern for an IPv4 address is the following:
The following Regex pattern will match most IPv6 addresses:(([0-9a-fA-F]:)[0-9a-fA-F]|([0-9a-fA-F]:):|([0-9a-fA-F]:):[0-9a-fA-F]|([0-9a-fA-F]:)(:[0-9a-fA-F])|([0-9a-fA-F]:)(:[0-9a-fA-F])|([0-9a-fA-F]:)(:[0-9a-fA-F])|([0-9a-fA-F]:)(:[0-9a-fA-F])|[0-9a-fA-F]:((:[0-9a-fA-F]))|:((:[0-9a-fA-F])|:)|fe80:(:[0-9a-fA-F])%[0-9a-zA-Z]|::(ffff(:0):)((254|(21|18)5)\.)(255|(24|18)1)|([0-9a-fA-F]:):((252|(21|17)8)\.)(252|(23|12)2))
How Do You Check If a String is an IP Address in Python?
The most robust way to check if a string is a valid IP address input or an invalid IP address in Python is to use the Python ipaddress module. This module provides several methods for validating, manipulating and otherwise working with IP addresses. You could also write a Regular Expression, but this is more error-prone and not usually advised.
Abstract’s IP Geolocation API comes with libraries, code snippets, guides, and more.