Reputation: 43
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:
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? :)
Upvotes: 4
Views: 4222
Reputation: 101176
ReceiveFrom
. Receive
is for TCP.BeginReceiveFrom
before the broadcast and EndReceiveFrom
after.Upvotes: 0
Reputation: 11190
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.
Upvotes: 1