c# - 如何使用 UDP 实现 Traceroute?

标签 c# tcp udp icmp traceroute

显然,ICMP 并不是创建 Traceroute 的唯一方法。 Thisthis answer 表示可以发送低 TTL 的 UDP 数据包(或任何其他数据包)并等待 ICMP 消息。

我将如何在 C# 中实现它?系统.IO.套接字? TCP对象?有人知道简单/最好的方法吗?

更新 1:

以下代码似乎在命中 TTL 时正确抛出异常。如何从返回的 UDP 数据包中提取信息?

我怎么知道我收到的 UDP 数据包是给我的(而不是我主机上的其他应用程序?)

   public  void PingUDPAsync(IPAddress _destination, short ttl)
    {
        // This constructor arbitrarily assigns the local port number.
        UdpClient udpClient = new UdpClient(21000);
        udpClient.Ttl = ttl;
       // udpClient.DontFragment = true;

        try
        {
            udpClient.Connect(_destination, 21000);

            // Sends a message to the host to which you have connected.
            Byte[] sendBytes = Encoding.ASCII.GetBytes("Is anybody there?");

            udpClient.Send(sendBytes, sendBytes.Length);


            //IPEndPoint object will allow us to read datagrams sent from any source.
            IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);

            // Blocks until a message returns on this socket from a remote host.
            Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
            string returnData = Encoding.ASCII.GetString(receiveBytes);

            // Uses the IPEndPoint object to determine which of these two hosts responded.
            Console.WriteLine("This is the message you received " +
                                         returnData.ToString());
            Console.WriteLine("This message was sent from " +
                                        RemoteIpEndPoint.Address.ToString() +
                                        " on their port number " +
                                        RemoteIpEndPoint.Port.ToString());

            udpClient.Close();
        }
        catch (SocketException socketException)
        {
            Console.WriteLine(socketException.ToString());
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }

    }

最佳答案

是的,System.Net.Sockets 应该为您提供发送/接收 UDP/TCP 数据包所需的所有原始对象。大量在线文档和示例,您在问题中包含的两篇文章非常有趣,是一个很好的起点:)

关于c# - 如何使用 UDP 实现 Traceroute?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7275992/

相关文章:

c# - 我的简单循环缓冲区无法正常工作

c# - 在c#中通过正则表达式提取多个字符串

java - 通过 TCP 套接字的 Avro 通信

java - Netty 关闭/停止 UDP 服务器

c - 带有 2 个 UDP 客户端的 UDP 服务器

c# - FileStream 和 System.IO.File 方法之间的文件访问差异

c - TCP 连接断开检测(如果中间链路断开)?

c - 在套接字中发送多个发送/接收

c - 发送广播服务器 -> 客户端并发回客户端 -> 服务器 UDP C Socket

c# - 在 C#/WPF 中使用 Canvas 遮盖另一个 Canvas