gpt4 book ai didi

python 套接字.sendto

转载 作者:太空宇宙 更新时间:2023-11-04 07:43:32 25 4
gpt4 key购买 nike

我是 python(3.3) 网络编程的新手,所以一开始我尝试编写一个基本的跟踪路由程序。其中一行代码是:

send_socket.sendto(512, '', (dest_name, port))

我在控制台中收到此行的错误,指出“TypeError:‘int’不支持缓冲区接口(interface)”。我尝试了一个 sting,但我用“str”而不是“int”得到了同样的错误。 I also looked at the documentation , 并尝试了其他几种配方但无济于事。

有没有人有这方面的经验?

import socket

def main(dest_name):
dest_addr = socket.gethostbyname(dest_name)
port = 33434
icmp = socket.getprotobyname('icmp')
udp = socket.getprotobyname('udp')
ttl = 1
while True:
recv_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
send_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, udp)
send_socket.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)
recv_socket.bind(('', port))
send_socket.sendto('', (dest_name, port))
curr_addr = None
curr_name = None
try:
_, curr_addr = recv_socket.recvfrom(512)
curr_addr = curr_addr[0]
try:
curr_name = socket.gethostbyaddr(curr_addr)[0]
except socket.error:
curr_name = curr_addr
except socket.error:
pass
finally:
send_socket.close()
recv_socket.close()

if curr_addr is not None:
curr_host = '%s (%s)' % (curr_name, curr_addr)
else:
curr_host = '*'
print "%d\t%s" % (ttl, curr_host)

ttl += 1
if curr_addr == dest_addr or ttl > max_hops:
break

if __name__ == '__main__':
main('www.google.com')

最佳答案

将字符串编码为字节,因为sendto不接受string对象

MESSAGE="Hello !!"
soc.sendto(MESSAGE.encode('utf-8'), (dest_name, port))

received_bytes, peer = con.recvfrom()
print("Received %s from %s:%u" % (received_bytes.decode('utf8'), peer[0], peer[1])

还值得注意的是,您可以使用这些网络功能发送任意数据,并且不需要编码文本。例如soc.sendto(b'\xff', (host, port)) 在 UDP 数据包中发送单个 FF 字节是完全有效的,并且不会解码为 UTF8 使用上面的代码。

关于 python 套接字.sendto,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13999393/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com