我已经编写了一个ICMP客户端和一个ICMP监听程序。我可以向监听程序发送自定义的回显请求,并且监听程序可以正确地解包它们。现在,我希望监听程序响应不是精确的回显,而是使用不同的数据集进行响应。这是我目前尝试过的方法:
ICMP客户端:
ICMP监听器:
这是监听器上出现的内容:
这是客户端上出现的内容:
因此,尽管向客户端发送了“good day”,但仍然收到“howdy pilgrim”。如何将“good day”发送回客户端?
ICMP客户端:
static void Main(string[] args)
{
Ping icmpClient = new Ping();
PingOptions options = new PingOptions();
options.DontFragment = true;
byte[] msg = Encoding.UTF8.GetBytes("howdy pilgrim");
while (true)
{
PingReply reply = icmpClient.Send("192.168.0.3", 60 * 1000, msg, options);
string responseReceived = Encoding.UTF8.GetString(reply.Buffer);
Console.WriteLine(DateTime.Now.ToString() + " Response from server: " + responseReceived);
Thread.Sleep(500);
}
}
ICMP监听器:
static void Main(string[] args)
{
while (true)
{
Socket icmpListener = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp);
icmpListener.Bind(new IPEndPoint(IPAddress.Parse("192.168.0.3"), 0));
icmpListener.IOControl(IOControlCode.ReceiveAll, new byte[] { 1, 0, 0, 0 }, null);
byte[] buffer = new byte[1024*1024];
EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
int bytesRead = icmpListener.ReceiveFrom(buffer, ref remoteEndPoint);
string receivedMsg = Encoding.UTF8.GetString(buffer, 28, bytesRead);
Console.WriteLine(DateTime.Now.ToString() + ": Received " + bytesRead + "B from " + remoteEndPoint + ": " + receivedMsg);
byte[] customResponse = Encoding.UTF8.GetBytes("good day");
int bytesSent = icmpListener.SendTo(customResponse, remoteEndPoint);
}
}
这是监听器上出现的内容:
![enter image description here](https://istack.dev59.com/EGn37.webp)
![enter image description here](https://istack.dev59.com/UCfaY.webp)