显然 ICMP 不是创建 Traceroute 的唯一方法。这个和这个答案表明可以发送具有低 TTL 的 UDP 数据包(或任何其他数据包)并等待 ICMP 消息。
我将如何在 C# 中实现它?System.IO.Sockets?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());
}
}