我是 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')