1

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

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

我在控制台中收到此行的错误,指出“TypeError:'int'不支持缓冲区接口”。我尝试了刺痛,但使用“str”而不是“int”得到了同样的错误。我还查看了文档,并尝试了其他几种配方,但均无济于事。

有人对此有经验吗?

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')
4

2 回答 2

4

将字符串编码为字节,因为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])

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

于 2015-03-01T04:53:59.857 回答
3

将消息转换为字符串:

sock.sendto(bytes(512), (dest_name, port))
于 2012-12-22T01:59:27.727 回答