UDP ping - 尝试获取端口不可达错误

3

我希望在客户端/服务器应用程序中实现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")
}

1
你尝试使用IPConn和ReadFromIP而不是ReadFromUDP了吗? - Brad Peabody
1个回答

0

检查回复消息的前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.

1
ReadFromUDP返回0字节,因此没有可读取的内容。任何ICMP处理都将在内部完成。conn并没有真正返回有意义的错误消息。 - ihsan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接