我是python(3.3)网络编程的新手,所以首先我尝试编写一个基本的traceroute程序。其中一行代码是:
send_socket.sendto(512, '', (dest_name, port))
我在控制台中收到此行的错误,指出" TypeError:' int'不支持缓冲接口"。我试着用刺痛了,我得到了同样的错误' 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')
答案 0 :(得分:3)
将邮件转换为字符串:
sock.sendto(bytes(512), (dest_name, port))
答案 1 :(得分:3)
将字符串编码为字节,因为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。