Receive Answer to UDP Broadcast (C#)

大憨熊 提交于 2019-12-23 12:59:25

问题


I'm trying to send a udp broadcast, and receive an answer in c#. While sending the broadcast works perfectly, i don't receive any answer in c#. But when i take a look with wireshark, i can see an answer has been sent:

  1. Sent from 192.168.0.141 to 192.168.0.255
  2. Sent from 192.168.0.105 to 255.255.255.255 (that would be the answer)


Wireshark Log:

1   0.000000    192.168.0.141   192.168.0.255   UDP Source port: 55487  Destination port: 17784
2   0.000851    192.168.0.105   255.255.255.255 UDP Source port: 17784  Destination port: 55487



Thats my c# code:

    private static byte[] SendBuffer = new byte[] { 1, 2, 3 };

    public static void SendAndReceiveBroadcast( byte[] data, IPEndPoint broadcastEndpoint )
    {

        using( Socket broadcastSocket = new Socket( AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp ) )
        {
            broadcastSocket.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1 );
            broadcastSocket.SendTo( data, broadcastEndpoint );
            receivePort = broadcastSocket.LocalEndPoint.ToString().Split( ':' )[1];
            Console.WriteLine( "Sent {0} from Port {1}", CollectionsHelper.ItemsToString( data, "{0:X2}" ), broadcastSocket.LocalEndPoint.ToString() );
            broadcastSocket.Close();
        }

        using( Socket receiveSocket = new Socket( AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp ) )
        {
            IPEndPoint broadcastAddress = new IPEndPoint( IPAddress.Any, Convert.ToInt32( receivePort ) );
            UdpClient udpClient = new UdpClient();
            udpClient.Client.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true );
            udpClient.Client.Bind( broadcastAddress );
            IPEndPoint remoteIP = new IPEndPoint( IPAddress.Any, Convert.ToInt32( receivePort ) );
            byte[] answer = udpClient.Receive( ref remoteIP );
        }
    }

The program stops when calling udpClient.Receive. Can anyone help me plz? :)


回答1:


  1. You should use ReceiveFrom. Receive is for TCP.
  2. If I'm not mistaken, broadcast messages are not queued. Call BeginReceiveFrom before the broadcast and EndReceiveFrom after.



回答2:


Since you are using the same process to send and receive, you need to open the receiver before you send the message, and you need to use udpClient.ReceiveAsync() and wait for the answer before you allow your program to shut down.



来源:https://stackoverflow.com/questions/6152489/receive-answer-to-udp-broadcast-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!