views:

231

answers:

1

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!

+3  A: 

It doesn't look like your SendBroadcast() socket is bound to a port so he's not going to receive anything. In fact your ReceiveBroadcast() socket is sending the reply back his own port so he will receive his own reply.

ReceiveBroadcast: binds to port 16789
SendBroadcast:    sends to port 16789
ReceiveBroadcast: receives datagram on port 16789
ReceiveBroadcast: sends reply to 16789
ReceiveBroadcast: **would receive own datagram if SendTo follwed by Receive**

You need to (a) have SendBroadcast() bind to a different port and change ReceiveBroadcast() send to that port (instead of his own endpoint ep), or (b) have both functions use the same socket object so they can both receive datagrams on port 16789.

John Kugelman
You're right, thank you!
eWolf