显然,ICMP 并不是创建 Traceroute 的唯一方法。 This和 this 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/