当收到UDP数据包时,该端口与监听端口不匹配
问题描述:
这不是问题,而是好奇心。我使用UDP创建了一个简单的发送/接收C#应用程序,主要遵循UdpClient上的MSDN示例。我有一个文本框用作发送或接收事件的日志;它打印时间戳以及从哪里发送/接收的内容。当收到UDP数据包时,该端口与监听端口不匹配
好奇心带着端口号进来。当程序在某个端口上侦听并收到一个数据包时,收到的数据包上的端口与它正在侦听的端口不匹配。
例如,这里的应用程序的截图(注:这即使使用不同的电脑发送仍然发生/接收):
它接收到的数据包就好了,这就是为什么并不是真正的“问题”,因为它正在工作。我只是好奇为什么收到的数据包上的端口显示不同于它正在监听的端口。我想知道如果也许它只是垃圾数据?
下面是当接收数据(使用我从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地址和端口,你看到的是源端口地址。
的公知端口用于将数据发送到,机器发送数据分配一个空闲的端口到报文的源端口,以便它可以从该端口上的服务器接收数据。
答
有在连接的每一端的端口号:你的进程正在监听公布的端口号,始发(客户端)端口号(这可能是一个不同的机器上)。
的通信信道作为一个IP地址和端口对,你看到的客户端端口是从必须预先知道服务器端口不同让客户知道向哪里发送到的每个端部。 – BhavO