【问题标题】:Python 3 - IPAddress checkPython 3 - IP地址检查
【发布时间】:2021-01-05 17:16:59
【问题描述】:

python 新手,但试图编写一些东西来检查用户输入的 IP 与 CIDR 是否存在,以查看 IP 在哪个 CIDR 中(如果有)...但是得到某种没有意义的 str 版本错误...

import ipaddress

ip2check = input("Enter IP Address:")
blocks = ['192.1.1.1/8', '0.0.0.0/16']
n = 1
print('Scanning through', len(blocks), 'CIDR blocks')
for x in blocks:
    print('Checking', blocks[n])
    breakpoint()
    if ip2check in ipaddress.IPv4Network(blocks[n]):
        print("IP is found in CIDR: ", blocks[n])
    else:
        print("IP not found in", blocks[n])

错误: 第 11 行,在

/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/codecs.py(309)init() -> def init(self, errors='strict')

或者它的: AttributeError: 'str' 对象没有属性 '_version'

【问题讨论】:

  • 什么错误
  • 请粘贴您运行的命令、完整输出和完整堆栈跟踪,没有这些信息很难帮助您

标签: python python-3.x ip-address


【解决方案1】:

好吧,如果您检查覆盖的 contains

,您正在尝试检查 objec IPv4Network 的成员资格
import ipaddress
import inspect

lines = inspect.getsource(ipaddress.IPv4Network.__contains__)

你得到

def __contains__(self, other):
        # always false if one is v4 and the other is v6.
        if self._version != other._version:
            return False
        # dealing with another network.
        if isinstance(other, _BaseNetwork):
            return False
        # dealing with another address
        else:
            # address
            return (int(self.network_address) <= int(other._ip) <=
                    int(self.broadcast_address))

这意味着该对象正在检查您正在比较的两个对象是否具有相同的版本、网络类型等等,但您正在做的是比较一个字符串与 IPv4Network,中的部分包含 用字符串对象没有的self._version检查版本控制,因此出现'string object does not have self._version'的错误

在简历中:您正在将字符串对象与 IPv4Network 对象进行比较,而这是您无法做到的。

【讨论】:

  • 如果我不清楚,坏线是if ip2check in ipaddress.IPv4Network(blocks[n]):
  • 嗯,有趣的是我不知道它包含所有其他信息 - 那么我该如何获取 IP 呢?还是网络地址或广播地址?
猜你喜欢
  • 2012-08-03
  • 1970-01-01
  • 1970-01-01
  • 2013-07-29
  • 1970-01-01
  • 2013-08-22
  • 2016-01-24
  • 1970-01-01
  • 2021-10-06
相关资源
最近更新 更多