检查用户输入的有效IP地址

时间:2020-07-31 13:08:38

标签: python python-3.x

我是Python的新手,并希望为下面的代码提供帮助。我希望能够验证最终用户是否在有效的IP地址中输入了密钥。我在网上搜索过,所有示例都太复杂了,难以理解,因此我在问。

如果可能的话,如果该人输入了无效的值,该代码也会循环返回。

input = 61.1.1.1

wanip = str(input("please key in WAN IP address:"))

5 个答案:

答案 0 :(得分:3)

您可以使用ipaddress模块。

例如:

import ipaddress

while True:
    try:
        a = ipaddress.ip_address(input('Enter IP address: '))
        break
    except ValueError:
        continue

print(a)

打印(例如):

Enter IP address: s
Enter IP address: a
Enter IP address: 1.1.1.1
1.1.1.1

答案 1 :(得分:1)

有多种方法可以执行此操作,如果您想要基于this guide的简单方法,则可以像这样使用RegExp:

import re
check = re.match(r'^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$', YOUR_STRING)
if check:
    print('IP valid')
else:
    print('IP not valid')

在您所处的情况下,它必须类似于:

wanip = str(input("please key in WAN IP address:"))
if not re.match(r'^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$', wanip):
    # Throw error here
# Continue with your code

如果在循环中:

import re

ip = None
while True:
    ip = str(input("please key in WAN IP address:"))
    if re.match(r'^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$', ip):
        # Say something to user
        break
    else:
        # Say something to user
        continue
print(ip)

答案 2 :(得分:1)

代码:

import ipaddress

try:
    user_ip = input("Enter adress: ")
    ip = ipaddress.ip_address(user_ip)
    print(f'{ip} is correct. Version: IPv{ip.version}')
except ValueError:
    print('Adress is invalid')

用法示例:

Enter adress: 23
Adress is invalid

Enter adress: 154.123.1.34
154.123.1.34 is correct. Version: IPv4

答案 3 :(得分:1)

检查一下

def validIPAddress(self, IP):
        
        def isIPv4(s):
            try: return str(int(s)) == s and 0 <= int(s) <= 255
            except: return False
            
        def isIPv6(s):
            if len(s) > 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"

答案 4 :(得分:1)

我认为一个更简单的解决方案是:

def isValid(ip):
    ip = ip.split(".")

    for number in ip:
        if not number.isnumeric() or int(number) > 255:
            return False
    
    return True

尽管使用正则表达式可能是更好的解决方案,但我不确定您是否已经熟悉它。