首页 文章

接收UDP数据包时,端口与侦听端口不匹配

提问于
浏览
0

这不是问题,而是好奇心 . 我使用UDP创建了一个简单的发送/接收C#应用程序,主要是遵循UdpClient上的MSDN示例 . 我有一个文本框作为发送或接收事物的日志;它打印时间戳以及从哪里发送/接收的内容 .

好奇心来自端口号码 . 当程序正在侦听某个端口并且它收到一个数据包时,收到的数据包上的端口与它正在侦听的端口不匹配 .

例如,这是应用程序的屏幕截图(注意:即使使用不同的计算机发送/接收,这仍然会发生):

它接收的数据包很好,这就是为什么这不是一个“问题”,因为它正在工作 . 我只是好奇为什么收到的数据包上的端口显示的不同于它正在侦听的端口 . 我想知道它是否只是垃圾数据?

这是接收数据时运行的代码(使用我从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.
    }
}

接收数据包时的端口号是无意义的垃圾数据,还是有某种用途?

2 回答

  • 0

    每个UDP数据包都有一个源和目标IP地址和端口,您看到的是源端口地址 .

    一个众所周知的端口用于向其发送数据,机器发送数据将一个空闲端口分配给数据包的源端口,以便它可以从该端口上的服务器接收数据 .

  • 0

    连接的每一端都有一个端口号:您的进程正在侦听的已发布端口号,以及始发(客户端)端口号(可能位于不同的计算机上) .

相关问题