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)
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? 🙂
ReceiveFrom.Receiveis for TCP.BeginReceiveFrombefore the broadcast andEndReceiveFromafter.