Receive replies to a UDP broadcast

O

OBones

Hi all,

I'm currently trying to receive replies to a UDP broadcast that I sent
and I can't get it to work. I know the datagrams are sent as I see
them with WireShark, but my C# code does not see them.
Here is how I intended things to work:

Socket socket = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
try
{
// Send data to the broadcast address
IPEndPoint broadcastIEP = new IPEndPoint(IPAddress.Broadcast,
port);
socket.Connect(broadcastIEP);
socket.Send(data);

// Wait for someone to respond
for (int i = 0; i < 50; i++)
{
int availableBytes = socket.Available;
if (availableBytes > 0)
{
byte[] buffer = new byte[availableBytes];
socket.Receive(buffer, 0, availableBytes,
SocketFlags.None);

return ASCIIEncoding.ASCII.GetString(buffer);
}
System.Threading.Thread.Sleep(100);
}
return "Nobody replied";
}
finally
{
socket.Close();
}


The intent is to send a UDP broadcast and wait for the first machine
that replies. The wait should stop after a while.
I must be doing something wrong here, but I'm quite lost as to what I
should be doing. I tried "ReceiveFrom", but it is a blocking call and
it never seems to return. I see the datagrams coming through (using
WireShark) but ReceiveFrom does not return.

Thanks for your help
Cheers
Olivier
 
N

not_a_commie

There is a whole slew of things that could be the issue here. In the
first place, you should be listening before you send. You'll need to
make another thread to do that or use the BeginReceive method. Second,
don't use the Available property. It's busted. Use the return value on
Receive to know how much data was put into your buffer instead. Third,
I'm pretty sure you'll need to bind to a port (with the Bind method)
to receive any data. In other words, you may need two sockets here.
One to send and one to receive. You may also need to set the option on
the sockets to allow multiple sockets to bind to the same address.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top