用于检查给定字符串是 IPv4 或 IPv6 还是无效的Python程序
给定一个字符串。任务是检查给定的字符串是 IPv4 还是 IPv6 还是无效的。
例子:
Input : “192.168.0.1”
Output : IPv4
Explanation : It is a valid IPv4 address
Input : “2001:0db8:85a3:0000:0000:8a2e:0370:7334”
Output : IPv6
Explanation : It is a valid IPv6 address
Input : “255.32.555.5”
Output : Invalid
Explanation : It is an invalid IPv4 address as the 3rd octet value(i.e 555) is greater 255.
Input : “250.32:555.5”
Output : Invalid
Explanation : The given string is invalid as it consists of both : and .
为了实现上述问题,我们将使用Python中的ipaddress
模块。该模块提供了在 IPv4 和 IPv6 地址和网络上创建、操作和操作的能力。
下面是实现。
from ipaddress import ip_address, IPv4Address
def validIPAddress(IP: str) -> str:
try:
return "IPv4" if type(ip_address(IP)) is IPv4Address else "IPv6"
except ValueError:
return "Invalid"
if __name__ == '__main__' :
# Enter the Ip address
Ip = "192.168.0.1"
print(validIPAddress(Ip))
Ip = "2001:0db8:85a3:0000:0000:8a2e:0370:7334"
print(validIPAddress(Ip))
Ip = "256.32.555.5"
print(validIPAddress(Ip))
Ip = "250.32:555.5"
print(validIPAddress(Ip))
输出 :
IPv4
IPv6
Invalid
Invalid