C# UdpClient 未收到wireshark 看到的数据包

问题描述 投票:0回答:1

我正在实现一个 udp 发现协议,其中我向本地网络广播消息,并从自定义硬件(或硬件模拟器)接收消息或多个响应,具体取决于网络上存在的实例数量。

我的广播工作正常,但是接收部分有一些问题:我看到了我发送的广播,但从未看到硬件响应。 我知道硬件正在发送广播,因为当我监控该端口上的流量时,我看到它们通过wireshark进入。

我做错了什么?

IPEndPoint receiveIpEndPoint = new IPEndPoint(IPAddress.Any, 777);

private List<string> FindIPs() {
        string message = "{\"TCS\":{\"IP\":\"" + GetLocalIPAddress().ToString() + "\", \"Port\":777}}"; 
        byte[] tempBytes = ASCIIEncoding.ASCII.GetBytes(message);
        IPEndPoint broadcastIpEndPoint = new IPEndPoint(IPAddress.Broadcast, 777); 

        // list of UdpClients to send 
        List<UdpClient> sendClients = new List<UdpClient>();
        foreach (NetworkInterface networkInterface in NetworkInterface.GetAllNetworkInterfaces()) {
            if ((!networkInterface.Supports(NetworkInterfaceComponent.IPv4)) ||
                (networkInterface.OperationalStatus != OperationalStatus.Up)) {
                continue;
            }

            IPInterfaceProperties adapterProperties = networkInterface.GetIPProperties();
            UnicastIPAddressInformationCollection unicastIPAddresses = adapterProperties.UnicastAddresses;
            IPAddress ipAddress = null;

            foreach (UnicastIPAddressInformation unicastIPAddress in unicastIPAddresses) {
                if (unicastIPAddress.Address.AddressFamily != AddressFamily.InterNetwork) {
                    continue;
                }
                ipAddress = unicastIPAddress.Address;
                break;
            }

            if (ipAddress == null) {
                continue;
            }

            UdpClient sendClient = new UdpClient(new IPEndPoint(ipAddress, 0));
            sendClients.Add(sendClient);
        }

        var udpreceive = new UdpClient(receiveIpEndPoint);
        udpreceive.BeginReceive(new AsyncCallback(ProcessUDPResponse), udpreceive);

        Log(message, LogManager.GetLogger("Sent UDP broadcast"));
        foreach (var udp in sendClients) {
            udp.EnableBroadcast = true;
            udp.Send(tempBytes, tempBytes.Length, broadcastIpEndPoint);
        }

        while(addresses.Count < 1) {

        }
        return addresses;
    }

    private void ProcessUDPResponse(IAsyncResult result) {
        UdpClient udp = result.AsyncState as UdpClient;
        string returnData = Encoding.ASCII.GetString(udp.EndReceive(result, ref receiveIpEndPoint));
        Console.WriteLine("**************           " + returnData.ToString());
        if (returnData.Contains("MAC")) {
            addresses.Add(receiveIpEndPoint.Address.ToString());
        }
        udp.BeginReceive(new AsyncCallback(ProcessUDPResponse), udp);
    }
c# network-programming udp udpclient
1个回答
0
投票

尝试使用 UdpClient Ttl。例如将其设置为 50。

© www.soinside.com 2019 - 2024. All rights reserved.