本文共 1415 字,大约阅读时间需要 4 分钟。
我们首先导入
import ipaddress
导入后,我们应该创建一个将IP地址作为参数的函数,然后对其进行验证。
def validate_ip(given_ip): try: ip = ipaddress.ip_address(given_ip) #slight issue with broadcast addresses, if IP ends in 255 or 0 then it should not be valid but will show as valid above so lets filter that out. ip_split = given_ip.split('.') if ip_split[3] != "0" and ip_split[3] != "255": return True else: return False except ValueError: return False except: print('Error : %s ip' % given_ip)if validate_ip("192.168.1.1"): print("Valid IP")
现在,我发现此模块的一个问题是它将说以0或255结尾的地址有效。现在从技术上讲它是有效的,但它们不是可用的地址,因此例如255是所谓的广播地址。因此,我添加了一个IF子句来过滤这两个值,并将它们标记为无效(如果显示的话)。
该代码是我的新ScanLan程序的一部分,可通过Github免费获得
您可以派生代码并在Repli.it上自己玩。
import ipaddressdef validate_ip(given_ip): try: ip = ipaddress.ip_address(given_ip) #slight issue with broadcast addresses, if IP ends in 255 or 0 then it should not be valid but will show as valid above so lets filter that out. ip_split = given_ip.split('.') if ip_split[3] != "0" and ip_split[3] != "255": return True else: return False except ValueError: return False except: print('Error : %s ip' % given_ip)if validate_ip("192.168.1.1"): print("Valid IP")
Python 3.8.2 (default,Feb 26 2020,02:56:10)
在这里还是要推荐下我自己建的Python学习群:553215015,群里都是学Python的,如果你想学或者正在学习Python ,欢迎你加入,大家都是软件开发党,不定期分享干货(只有Python软件开发相关的),包括我自己整理的一份2020最新的Python进阶资料和零基础教学,欢迎进阶中和对Python感兴趣的小伙伴加入!
转载地址:http://ruhxf.baihongyu.com/