【python】判断一个地址是ipv4还是ipv6

from netaddr.ip import IPAddress

def isIP4or6(cfgstr):
	ipFlg = False

	if '/' in cfgstr:
		text = cfgstr[:cfgstr.rfind('/')]
	else:
		text = cfgstr
	
	try:
		addr = IPAddress(text)
		ipFlg = True
	except:
		ipFlg = False

	if ipFlg == True:
		return addr.version
	else:
		return False
		
str_IPaddress = '192.168.1.2'
	
if isIP4or6(str_IPaddress) == 4:
	print('It is ipv4.')
elif isIP4or6(str_IPaddress) == 6:
	print('It is ipv6.')
else:
	print('It is neither ipv4 nor ipv6.')

  

posted on 2018-08-24 14:29  芽衣  阅读(8026)  评论(0编辑  收藏  举报

导航