2013-10-01 29 views
1

我想爲我的客戶端/服務器應用程序實現UDP ping,其中客戶端將UDP數據包發送到任何服務器的臨時端口,以嘗試獲取ICMP端口不可訪問的答覆。UDP ping - 嘗試獲取端口無法訪問錯誤

我有以下代碼。 ReadFromUDP()返回從套接字讀取的錯誤=零和0字節。

問題是,我如何從服務器讀取特定端口不可達的ICMP回覆?

conn, _ := net.ListenUDP("udp4", src) 
defer conn.Close() 

t := time.Now() 
conn.SetDeadline(t.Add(100 * time.Millisecond)) 
conn.SetReadDeadline(t.Add(250 * time.Millisecond)) 

w, e := conn.WriteTo([]byte("PING"), dst) 
if e != nil { 
    return nil, errors.New("Failed to send UDP4 ping request") 
} 

r, _, e := conn.ReadFromUDP(b4) 
if e != nil { 
    return nil, errors.New("Failed to read UDP4 response packets") 
} 
+1

你嘗試使用IPConn和ReadFromIP代替ReadFromUDP? –

回答

0

檢查類型3,代碼3(端口不可達)前2個字節的應答消息:

引述RFC792

Destination Unreachable Message 

    0     1     2     3 
    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 
    |  Type  |  Code  |   Checksum    | 
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 
    |        unused       | 
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 
    |  Internet Header + 64 bits of Original Data Datagram  | 
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 

    IP Fields: 

    Destination Address 

     The source network and address from the original datagram's data. 

    ICMP Fields: 

    Type 

     3 

    Code 

     0 = net unreachable; 

     1 = host unreachable; 

     2 = protocol unreachable; 

     3 = port unreachable; 

     4 = fragmentation needed and DF set; 

     5 = source route failed. 
+1

ReadFromUDP返回0字節,所以沒有什麼可讀的。任何ICMP處理都將在內部完成。 conn並沒有真正返回有意義的錯誤信息。 – ihsan