Python验证IP合法性

笔者采用第三方库IPy。

IPy库的安装请自行查找。

IPy库是一个处理IP比较强大的库,其他功能请自行挖掘。

示例代码如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2016 KigKrazy

from __future__ import absolute_import, division, print_function, \
	with_statement

import IPy

def  is_ip(address):
	try:
		IPy.IP(address)
		return True
	except Exception as  e:
		return False
		
def test():
	'''
	测试IPV4格式的IP
	'''
	print('测试IPV4格式的IP-----------------------------------------------------')
	if is_ip('127.0.0.1'):
		print('i \'m ip %s' %('127.0.0.1') )
	else:
		print('i \'m not ip %s' %('127.0.0.1') )
		
	if is_ip('127.0.0.300'):
		print('i \'m ip %s' %('127.0.0.300') )
	else:
		print('i \'m not ip %s' %('127.0.0.300') )

	if is_ip('127.0.0.0/30'):
		print('i \'m ip %s' %('127.0.0.0/30') )
	else:
		print('i \'m not ip %s' %('127.0.0.0/30') )

	'''
	测试IPV6格式的IP
	'''
	print('测试IPV6格式的IP-----------------------------------------------------')
	if is_ip('::ffff:1'):
		print('i \'m ip %s' %('::ffff:1') )
	else:
		print('i \'m not ip %s' %('::ffff:1') )
	
	if is_ip('::ffff:1s'):
		print('i \'m ip %s' %('::ffff:1s') )
	else:
		print('i \'m not ip %s' %('::ffff:1s') )

	if is_ip('FEC0:0:0:0001::/64'):
		print('i \'m ip %s' %('FEC0:0:0:0001::/64') )
	else:
		print('i \'m not ip %s' %('FEC0:0:0:0001::/64') )
	
	
if __name__ == '__main__':
	test()




你可能感兴趣的:(Python)