在 2.7 中使用套接字时出现 Python 类型错误

发布于 2024-11-07 09:30:09 字数 779 浏览 1 评论 0原文

在 python 2.7 中使用套接字时,我遇到了如下类型错误:

TypeError: coercing to Unicode: need string or buffer, instance found。

我确信这与 python2 和 python3 在 unicode 方面的差异有关。但我对这些差异还不够熟悉,无法缩小解决问题的范围。我确信我知道问题出在哪里,但我谷歌未能帮助我找到解决方案。这是我遇到问题的代码段。

from IPy import IP
ip = IP(sys.argv[1])
for x in ip:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    svr = (x, 25)
    s.connect(svr)
    data = s.recv(2048)
    s.close()
    print(repr(data))

这是错误的确切打印输出:

Traceback (most recent call last):
File "relayscanner.py", line 17, in <module>
s.connect(tgt)
File "C:\Python27\lib\socket.py", line 222, in meth
return getattr(self._sock,name)(*args)
TypeError: coercing to Unicode: need string or buffer, instance found

Working with sockets in python 2.7, and I've encountered a Type error as follows:

TypeError: coercing to Unicode: need string or buffer, instance found.

I'm sure this has something to do with the differences between python2 and python3 in terms of unicode. But I'm not familiar enough with the differences to narrow down how to fix the problem. I'm sure I know where the problem is, but I google has failed to assist me in finding a solution. Here's the code segment I'm having problems with.

from IPy import IP
ip = IP(sys.argv[1])
for x in ip:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    svr = (x, 25)
    s.connect(svr)
    data = s.recv(2048)
    s.close()
    print(repr(data))

Here is the exact printout of the error:

Traceback (most recent call last):
File "relayscanner.py", line 17, in <module>
s.connect(tgt)
File "C:\Python27\lib\socket.py", line 222, in meth
return getattr(self._sock,name)(*args)
TypeError: coercing to Unicode: need string or buffer, instance found

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一枫情书 2024-11-14 09:30:09

我认为问题是您给了 socket.connect() 一个 IPy.IP 对象,但它需要一个字符串。首先尝试将其强制为字符串,即:

svr = (str(x), 25)

I think the problem is that you are giving socket.connect() an IPy.IP object, but it expects a string. Try coercing it to a string first, IE:

svr = (str(x), 25)
全部不再 2024-11-14 09:30:09

看起来它不喜欢服务器元组中具有 x 值的内容,我建议通过每次迭代检查 x 值。如果它是一个对象,请尝试 .strNormal() 方法。

It looks like it doesn't like something with the value of x in your server tuple I recommend checking the value of x through each iteration. If it's an object, try the .strNormal() method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文