接收UDP包时,端口与监听端口不匹配
When receiving UDP packets, the port does not match the listen port
这不是问题,而是一种好奇心。我使用 UDP 创建了一个简单的 send/receive C# 应用程序,主要遵循 UdpClient 上的 MSDN 示例。我有一个文本框作为发送或接收时的日志;它打印时间戳以及 sent/received 来自哪里。
好奇来自于端口号。当程序在某个端口上侦听并接收到数据包时,接收到的数据包上的端口与它正在侦听的端口不匹配。
例如,这是应用程序的屏幕截图(注意:即使使用不同的计算机 send/receive 也会发生这种情况):
它可以很好地接收数据包,这就是为什么它不是真正的 "problem",因为它正在工作。我只是好奇为什么接收到的数据包上的端口显示与它正在侦听的端口不同。我想知道这是否只是垃圾数据?
这是在收到数据时运行的代码(使用我从 MSDN 获取的 AsyncCallback):
private void ReceiveCallback(IAsyncResult ar)
{
try {
// Pull the socket from the AsyncResult parameter
UdpState state = (UdpState)(ar.AsyncState);
UdpClient udp = state.udp;
IPEndPoint end = state.endpoint;
// Grab and convert the message into a string
byte[] recvBytes = udp.EndReceive(ar, ref end);
string recvString = Encoding.ASCII.GetString(recvBytes);
/* Here's where it's logging the IPEndPoint onto the console.
* Is the port meaningless when receiving a packet, and that's why it's
* always something random? Or is there some meaning to it that I'm
* unaware of? */
ConsoleLog(end.ToString() + " Recv: " + recvString);
// Start the listen cycle again so this will be called again
listener.BeginReceive(new AsyncCallback(ReceiveCallback), state);
} catch (ObjectDisposedException) {
// Do nothing - Expected error when the UDP Listener is closed.
}
}
收包时的端口号是无意义的垃圾数据,还是有什么用处?
连接的每一端都有一个端口号:您的进程正在侦听的已发布端口号,以及原始(客户端)端口号(可能在不同的机器上)。
每个UDP数据包都有一个源和目的IP地址和端口,你看到的是源端口地址。
一个众所周知的端口用于发送数据,发送数据的机器为数据包的源端口分配一个空闲端口,以便它可以在该端口上从服务器接收数据。
这不是问题,而是一种好奇心。我使用 UDP 创建了一个简单的 send/receive C# 应用程序,主要遵循 UdpClient 上的 MSDN 示例。我有一个文本框作为发送或接收时的日志;它打印时间戳以及 sent/received 来自哪里。
好奇来自于端口号。当程序在某个端口上侦听并接收到数据包时,接收到的数据包上的端口与它正在侦听的端口不匹配。
例如,这是应用程序的屏幕截图(注意:即使使用不同的计算机 send/receive 也会发生这种情况):
它可以很好地接收数据包,这就是为什么它不是真正的 "problem",因为它正在工作。我只是好奇为什么接收到的数据包上的端口显示与它正在侦听的端口不同。我想知道这是否只是垃圾数据?
这是在收到数据时运行的代码(使用我从 MSDN 获取的 AsyncCallback):
private void ReceiveCallback(IAsyncResult ar)
{
try {
// Pull the socket from the AsyncResult parameter
UdpState state = (UdpState)(ar.AsyncState);
UdpClient udp = state.udp;
IPEndPoint end = state.endpoint;
// Grab and convert the message into a string
byte[] recvBytes = udp.EndReceive(ar, ref end);
string recvString = Encoding.ASCII.GetString(recvBytes);
/* Here's where it's logging the IPEndPoint onto the console.
* Is the port meaningless when receiving a packet, and that's why it's
* always something random? Or is there some meaning to it that I'm
* unaware of? */
ConsoleLog(end.ToString() + " Recv: " + recvString);
// Start the listen cycle again so this will be called again
listener.BeginReceive(new AsyncCallback(ReceiveCallback), state);
} catch (ObjectDisposedException) {
// Do nothing - Expected error when the UDP Listener is closed.
}
}
收包时的端口号是无意义的垃圾数据,还是有什么用处?
连接的每一端都有一个端口号:您的进程正在侦听的已发布端口号,以及原始(客户端)端口号(可能在不同的机器上)。
每个UDP数据包都有一个源和目的IP地址和端口,你看到的是源端口地址。
一个众所周知的端口用于发送数据,发送数据的机器为数据包的源端口分配一个空闲端口,以便它可以在该端口上从服务器接收数据。