无法使用 UdpClient 捕获接收到的数据报

Cannot capture received datagram with UdpClient

我正在尝试向设备发送 UDP 命令并从同一设备接收 UDP 响应。发送工作正常。我可以看到数据报离开(通过 WireShark)。我还可以从设备(同样通过 WireShark)看到数据报 return。命令发出和响应接收之间的周转时间约为 15 毫秒。

代码

Byte[] button_click(Byte[] command) 
{
    // Device exists at a particular IP address and listens for UDP commands on a particular port
    IPEndPoint SendingEndpoint = new IPEndPoint(DEVICE_IP, DEVICE_PORT);

    // Device always sends from port 32795 to whatever port the command originated from on my machine
    IPEndPoint ReceivingEndpoint = new IPEndPoint(DEVICE_IP, 32795);

    // Sending client
    sendingClient = new UdpClient();
    sendingClient.Connect(SendingEndpoint);

    // Receiving client
    receivingClient = new UdpClient();
    receivingClient.Client.ReceiveTimeout = RECEIVE_TIMEOUT; // timeout after 4 seconds
    receivingClient.Connect(receivingEndpoint);

    // Send command and wait for response
    Byte[] response = null;
    try
    {
        sendingClient.Connect(DEVICE_IP, DEVICE_PORT);
        sendingClient.Send(command, command.Length);
        response = receivingClient.Receive(ref receivingEndpoint);
    }
    catch (SocketException e)
    {
        // If we timeout, discard SocketException and return null response
    }

    return response;
}

问题

我无法在我的应用程序中捕获接收到的数据报。当我 运行 上述代码时,出现以下异常:

"A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond."

Whosebug 上有类似的帖子,但其中 none 似乎解决了我的情况。而且我已经确认我的数据包没有在我的防火墙中被清除。

我做错了什么?

如果使用sendingClient接收,就可以得到正确的消息。原因是IP由Host+Port+Protocol组成,当发送点连接到设备发送消息时,设备收到Endpoint和与发送Endpoint配对的UDP。当接收客户端尝试接收消息时,没有任何反应,因为 UDP 是对等协议,接收客户端的端口必须与发送客户端不同,因此接收客户端什么也得不到。以下是我的示例代码,供大家参考。

        IPAddress address;
        IPAddress.TryParse("127.0.0.1", out address);
        IPEndPoint recPoint = new IPEndPoint(address, 13154);
        // IPEndPoint sendPoint = new IPEndPoint(address, 9999);
        UdpClient send = new UdpClient(9999);
        send.Connect(recPoint);
        Byte[] response = null;
        Byte[] command = System.Text.Encoding.Default.GetBytes("NO one");
        try
        {
            send.Send(command, command.Length);
            response = send.Receive(ref recPoint);
        }
        catch(Exception ex) {
            Console.WriteLine(ex.ToString());
        }

根据Alex的回答,我更新了完整的示例代码以供参考。

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Net;

namespace console
{
    class Program
    {
        static void Main(string[] args)
        {
            IPAddress address;
            IPAddress.TryParse("192.168.14.173", out address);
            IPEndPoint recPoint = new IPEndPoint(address, 13154);
            IPEndPoint recAnyPoint = new IPEndPoint(IPAddress.Any, 13154);
            IPEndPoint ipPoint = new IPEndPoint(IPAddress.Parse("192.168.14.174"), 13154);

            // IPEndPoint sendPoint = new IPEndPoint(address, 9999);
            UdpClient send = new UdpClient();
            send.ExclusiveAddressUse = false;
            // no need to use the low level socketoption 
            // send.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            send.Client.Bind(recAnyPoint);
            send.Connect(ipPoint);
            UdpClient receive = new UdpClient();

            receive.ExclusiveAddressUse = false;
            // receive.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            receive.Client.Bind(recPoint);
            receive.Connect(ipPoint);
            Byte[] response = null;
            Byte[] command = System.Text.Encoding.Default.GetBytes("NO one");
            try
            {
                send.Send(command, command.Length);
                response = receive.Receive(ref ipPoint);
                Console.WriteLine(System.Text.Encoding.Default.GetString(response));
            }
            catch(Exception ex) {
                Console.WriteLine(ex.ToString());
            }
        }
    }
}

我解决了这个问题。解决方案需要两件事:

  1. 发送和接收客户端必须使用相同的本地端口
  2. 发送客户端必须使用 IPEndPoint 声明为 IPAddress.Any 接收客户端必须使用 IPEndPoint 声明为我本地机器的确切 IP 地址

代码

// Create endpoints
IPEndPoint DeviceEndPoint = new IPEndPoint(DEVICE_IP, DEVICE_PORT);
IPEndPoint localEndPointAny = new IPEndPoint(IPAddress.Any, LOCAL_PORT); // helps satisfy point 2
IPEndPoint localEndPointExplicit = new IPEndPoint(IPAddress.Parse(GetLocalIPAddress()), LOCAL_PORT);  // helps satisfy point 2
IPEndPoint incomingEndPoint = null; // Later populated with remote sender's info

// Create sending client
UdpClient sendingClient = new UdpClient();
sendingClient.ExclusiveAddressUse = false; // Going to use same port for outgoing and incoming (helps satisfy point 1)
sendingClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); // helps satisfy point 1
sendingClient.Client.Bind(localEndPointAny); // Any outgoing IP address will do

// Create receiving client
UdpClient receivingClient = new UdpClient();
receivingClient.Client.ReceiveTimeout = RECEIVE_TIMEOUT; // 4000 milliseconds
receivingClient.ExclusiveAddressUse = false; // Going to use same port for outgoing and incoming (helps satisfy point 1)
receivingClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); // helps satisfy point 1
receivingClient.Client.Bind(localEndPointExplicit); // Must explicitly give machine's outgoing IP address

获取本地IP地址的代码can be found here