专栏首页一日一工具python之ip校验简单总结

python之ip校验简单总结

ip地址有效性校验

socket模块

Note:不能校验ip的长度,可以校验每个IP中每段的有效性

代码:

import socket
import tracebackdef is_ip(ipaddr):
   resp = True
   try:
       socket.inet_aton(ipaddr)
   except Exception, e:
       traceback.print_exc()
       resp = False
   return respif __name__ == '__main__':
   ip = sys.argv[1]
   if is_ip(ip):
      print "{0} 是合法地址".format(ip)

效果:

[root@zhuima ~ 16:22:55]# python check_ip.py 12.34.34.34
12.34.34.34 是合法地址
[root@zhuima ~ 16:23:04]# python check_ip.py 12.34
12.34 是合法地址
[root@zhuima ~ 16:23:08]# python check_ip.py 12.34.34.345
Traceback (most recent call last):
 File "check_ip.py", line 30, in is_ip
   socket.inet_aton(ip)
error: illegal IP address string passed to inet_aton
[root@zhuima ~ 16:23:20]#

ipaddress模块

Note: 在python2下需要注意点,传入的一定要是unicode

代码:

import ipaddress
import tracebackdef is_ip(ipaddr):
   resp = True
   try:
       ipaddress.ip_address(u'{0}'.format(ipaddr))
   except Exception, e:
       traceback.print_exc()
       resp = False
   return respif __name__ == '__main__':
   ip = sys.argv[1]
   if is_ip(ip):
      print "{0} 是合法地址".format(ip)

python2下需要注意,要使用unicode

代码:

bpython version 0.16 on top of Python 2.6.6 /usr/bin/python
>>> import ipaddress
>>> ipaddress.ip_address('192.168.0.44')
Traceback (most recent call last):
 File "<input>", line 1, in <module>
   ipaddress.ip_address('192.168.0.44')
 File "/usr/lib/python2.6/site-packages/ipaddress.py", line 163, in ip_address
   ' a unicode object?' % address)
AddressValueError: '192.168.0.44' does not appear to be an IPv4 or IPv6 address. Did you pass in a bytes (str in Python 2) instead of a unicode object?

效果:

[root@zhuima ~ 16:37:18]# python check_ip.py 192.168.202.98
192.168.202.98 是合法地址
[root@zhuima ~ 16:37:19]# python check_ip.py 192.168.202.98s
Traceback (most recent call last):
 File "check_ip.py", line 52, in is_ip
   ipaddress.ip_address(u'{0}'.format(ipaddr))
 File "/usr/lib/python2.6/site-packages/ipaddress.py", line 166, in ip_address
   address)
ValueError: u'192.168.202.98s' does not appear to be an IPv4 or IPv6 address
192.168.202.98s 不是一个合法的地址
[root@zhuima ~ 16:37:22]# python check_ip.py 192.168.202.9865
Traceback (most recent call last):
 File "check_ip.py", line 52, in is_ip
   ipaddress.ip_address(u'{0}'.format(ipaddr))
 File "/usr/lib/python2.6/site-packages/ipaddress.py", line 166, in ip_address
   address)
ValueError: u'192.168.202.9865' does not appear to be an IPv4 or IPv6 address
192.168.202.9865 不是一个合法的地址
[root@zhuima ~ 16:37:26]#

IPy模块

Note: 不能校验ip的长度,可以校验每个IP中每段的有效性,和socket结果类似

代码:

import IPydef is_ip(ipaddr):
   resp = True
   try:
       IPy.IP(ipaddr)
   except Exception, e:
       traceback.print_exc()
       resp = False
   return respif __name__ == '__main__':
   ip = sys.argv[1]
   if is_ip(ip):
      print "{0} 是合法地址".format(ip)

效果:

[root@zhuima ~ 16:41:19]# python check_ip.py 1.1.2.3
1.1.2.3 是合法地址
[root@zhuima ~ 16:41:21]# python check_ip.py 1.1
1.1 是合法地址
[root@zhuima ~ 16:41:24]# python check_ip.py 1.1.
Traceback (most recent call last):
 File "check_ip.py", line 43, in is_ip
   IPy.IP(ipaddr)
 File "/usr/lib/python2.6/site-packages/IPy.py", line 246, in __init__
   (self.ip, parsedVersion) = parseAddress(ip)
 File "/usr/lib/python2.6/site-packages/IPy.py", line 1414, in parseAddress
   bytes = [int(x) for x in bytes]
ValueError: invalid literal for int() with base 10: ''
[root@zhuima ~ 16:41:25]# python check_ip.py 1.1.345sdf.sdfd
Traceback (most recent call last):
 File "check_ip.py", line 43, in is_ip
   IPy.IP(ipaddr)
 File "/usr/lib/python2.6/site-packages/IPy.py", line 246, in __init__
   (self.ip, parsedVersion) = parseAddress(ip)
 File "/usr/lib/python2.6/site-packages/IPy.py", line 1414, in parseAddress
   bytes = [int(x) for x in bytes]
ValueError: invalid literal for int() with base 10: '345sdf'
[root@zhuima ~ 16:41:31]#

netaddr模块

Note: 相对来说比较好,python2下推荐使用

代码:

from netaddr import valid_ipv4def is_ip(ipaddr):
   if not valid_ipv4(ipaddr,flags=1):
       print "{0} 不合法".format(ipaddr)if __name__ == '__main__':
   ip = sys.argv[1]
   is_ip(ip)

效果:

[root@zhuima ~ 16:41:59]# vim check_ip.py
[root@zhuima ~ 16:43:05]# python check_ip.py 1.1
1.1 不合法
[root@zhuima ~ 16:43:08]# python check_ip.py 1.1.1
1.1.1 不合法
[root@zhuima ~ 16:43:10]# python check_ip.py 1.1.1.1
[root@zhuima ~ 16:43:17]# python check_ip.py sdfsad
sdfsad 不合法
[root@zhuima ~ 16:43:22]# python check_ip.py sdfsad.sfda.sdf.sdf
sdfsad.sfda.sdf.sdf 不合法
[root@zhuima ~ 16:43:27]# python check_ip.py 192.168.202.2
[root@zhuima ~ 16:43:34]#

网上其他方式

正则

https://gist.github.com/youngsterxyf/5088954

代码:

import redef ipFormatChk(ip_str):
  pattern = r"\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"
  if re.match(pattern, ip_str):      
       return True   
   else:      
       return False

python高阶函数

https://gist.github.com/youngsterxyf/5088954

代码:

def ip_check(ip):
   q = ip.split('.')
    return len(q) == 4 and len(filter(lambda x: x >= 0 and x <= 255, \        map(int, filter(lambda x: x.isdigit(), q)))) == 4

总结

  • python2下使用netaddr模块,python3下使用ipaddress模块
  • 如有错误,请指正,谢谢

本文分享自微信公众号 - 追马Linux(zhuima_k8s),作者:追马

原文出处及转载信息见文内详细说明,如有侵权,请联系 yunjia_community@tencent.com 删除。

原始发表时间:2017-06-26

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • [抛砖引玉]shell面试之对比文件

    追马
  • 基础架构组建Tips

    追马
  • python程序打包新姿势(nuitka)

    Nuitka is a Python compiler written in Python. It's fully compatible with Python...

    追马
  • Java微信开发_Exception_02_"errcode":40164,"errmsg":"invalid ip 61.172.68.219, not in whitelist hint

    shirayner
  • 用Python爬虫抓取免费代理IP

    -- Illustrations by Ash Thorp & Maciej Kuciara --

    Python中文社区
  • django request 获取请求的 IP 地址

    KEVINGUO_CN
  • 调用python-nmap实现扫描局域网

    使用环境:Raspberry 3b+ +netifaces+python-nmap+nmap

    py3study
  • python实现主机批量管理

        在日常的运维工作中批量对主机的是很常见的,市面上也有许多主机批量管理的软件,但有时候这些软件并不能完全的满足我们的需求。python中刚好提供了关于主机...

    py3study
  • 关于伪造ip的可行性

    今晚,用curl进一个网站发现ip被限制访问了,然后我又开始了百度伪造请求ip的方法

    仙士可
  • 【Go】获取用户真实的ip地址

    用户请求到达提供服务的服务器中间有很多的环节,导致服务获取用户真实的 ip 非常困难,大多数的框架及工具库都会封装各种获取用户真实 ip 的方法,在 exne...

    thinkeridea

扫码关注云+社区

领取腾讯云代金券