I'm trying to send a broadcast and then let the server reply to it:
public static void SendBroadcast()
{
byte[] buffer = new byte[1024];
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
socket.Connect(new IPEndPoint(IPAddress.Broadcast, 16789));
socket.Send(System.Text.UTF8Encoding.UTF8.GetBytes("Anyone out there?"));
var ep = socket.LocalEndPoint;
socket.Close();
socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Bind(ep);
socket.Receive(buffer);
var data = UTF8Encoding.UTF8.GetString(buffer);
Console.WriteLine("Got reply: " + data);
socket.Close();
}
public static void ReceiveBroadcast()
{
byte[] buffer = new byte[1024];
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
var iep = new IPEndPoint(IPAddress.Any, 16789);
socket.Bind(iep);
var ep = iep as EndPoint;
socket.ReceiveFrom(buffer, ref ep);
var data = Encoding.UTF8.GetString(buffer);
Console.WriteLine("Received broadcast: " + data + " from: " + ep.ToString());
buffer = UTF8Encoding.UTF8.GetBytes("Yeah me!");
socket.SendTo(buffer, ep);
socket.Close();
}
The broadcast arrives fine, but the reply doesn't. No exception is thrown. Can anyone help me? Do I have to open a new connection for the reply or something?
EDIT: Changed my code a bit, and now it works! Thanks for your reply!