2011-02-03 94 views
3

我有一個用於Unix系統的traceroute Python程序,它打印出從本地機器到目的地的數據包路徑 - 也就是數據包經過的路由器序列。問題是我得到一個顯示輸出:需要幫助解決Unix中traceroute的問題

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')** 
+0

你應該讀一遍[這裏](http://stackoverflow.com/editing-help)。 – 2011-02-03 15:55:15

回答

2

的traceroute/tracert的行爲方式在Linux和Windows。

Linux將發送一個TTL遞減的UDP數據包並偵聽ICMP響應。 Windows發送ICMP迴應請求並偵聽ICMP響應。

由於UDP數據包被阻塞,Python版本失敗。

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