gpt4 book ai didi

python - 需要帮助解决 Unix 中的 traceroute 问题

转载 作者:行者123 更新时间:2023-11-28 17:53:41 26 4
gpt4 key购买 nike

我有一个用于 Unix 系统的 traceroute Python 程序,它打印出数据包从本地机器到达目的地所采用的路径——即数据包经过的路由器序列。问题是我得到的输出显示:

traceroute to yahoo.co.in (68.180.206.184), 30 hops max, 60 byte packets

1 * * *
2 * * *
3 * * *
4 * * *
5 * * *
6 * * *
7 * * *
8 * * *
9 * * *
.
.
.
30 * * *

我有 DSL 连接。该程序与 Windows 命令行 (cmd.exe) 配合使用效果很好。上面输出的确切原因是什么?

代码如下所示:

#!/usr/bin/python
import socket
def main(dest_name):
dest_addr = socket.gethostbyname(dest_name)
port = 33434
max_hops = 30
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('yahoo.co.in')**

最佳答案

traceroute/tracert 在 Linux 和 Windows 上的行为不同。

Linux 将发送一个 TTL 递减的 UDP 数据包并监听 ICMP 响应。 Windows 发送 ICMP 回显请求并监听 ICMP 响应。

Python 版本失败,因为 UDP 数据包被阻止。

On Unix-like operating systems, the traceroute utility by default uses User Datagram Protocol (UDP) datagrams with destination port numbers from 33434 to 33534. The traceroute utility usually has an option to specify use of ICMP echo request (type 8) instead, as used by the Windows tracert utility.

http://en.wikipedia.org/wiki/Traceroute

关于python - 需要帮助解决 Unix 中的 traceroute 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4888333/

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