UDP ping - 尝试获取端口无法访问错误



我想为我的客户端/服务器应用程序实现UDP ping,其中客户端将UDP数据包发送到服务器的任何临时端口,以尝试获得ICMP端口无法访问的回复。

我有以下代码。ReadFromUDP() 返回错误 = nil 和从套接字读取的 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")
}

检查回复消息的前 2 个字节,了解类型 3,代码 3(端口无法访问):

引用 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.

最新更新