python中使用socket模块验证IP地址的正确性。
代码:
#!/bin/python
#site: www.jb200.com
#
import socket
#--验证ipv4格式的IP地址
def is_valid_ipv4_address(address):
try:
addr= socket.inet_pton(socket.AF_INET, address)
except AttributeError: # no inet_pton here, sorry
try:
addr= socket.inet_aton(address)
except socket.error:
return False
return address.count('.') == 3
except socket.error: # not a valid address
return False
return True
#--验证ipv6格式的IP地址
def is_valid_ipv6_address(address):
try:
addr= socket.inet_pton(socket.AF_INET6, address)
except socket.error: # not a valid address
return False
return True