Receive Answer to UDP Broadcast (C#)
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:
- Sent from 192.168.0.141 to 192.168.0.255
- Sent from 192.168.0.105 to 255.255.255.255 (that would be the answer)
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( IPAddr开发者_开发技巧ess.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? :)
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.
- You should use
ReceiveFrom
.Receive
is for TCP. - If I'm not mistaken, broadcast messages are not queued. Call
BeginReceiveFrom
before the broadcast andEndReceiveFrom
after.
精彩评论