2

I am trying to write some code that does a UDP broadcast, and then listens to replies from remote servers saying they exist. It's used to identify machines running a server app on the subnet so basically sends out a "who's there?" and listens for all the replies.

I have this in Java (works perfectly) where it sends a DatagramPacket broadcasting to a group address of 224.168.101.200. and then has a worker thread that keeps listening for incoming DatagramPackets coming in on the same socket.

This and this are not the answer as they say how to have the send and listen on different machines.

Community
  • 1
  • 1
David Thielen
  • 28,723
  • 34
  • 119
  • 193

1 Answers1

1

Just made a working example for you, you could compare what went wrong. I created a windows forms applications with 2 textboxes and a button.

public partial class Form1 : Form
{
    private int _port = 28000;

    private string _multicastGroupAddress = "239.1.1.1";

    private UdpClient _sender;
    private UdpClient _receiver;

    private Thread _receiveThread;

    private void UpdateMessages(IPEndPoint sender, string message)
    {
        textBox1.Text += $"{sender} | {message}\r\n";
    }

    public Form1()
    {
        InitializeComponent();

        _receiver = new UdpClient();
        _receiver.JoinMulticastGroup(IPAddress.Parse(_multicastGroupAddress));
        _receiver.Client.Bind(new IPEndPoint(IPAddress.Any, _port));

        _receiveThread = new Thread(() =>
        {
            while (true)
            {
                IPEndPoint sentBy = new IPEndPoint(IPAddress.Any, _port);
                var dataGram = _receiver.Receive(ref sentBy);

                textBox1.BeginInvoke(
                    new Action<IPEndPoint, string>(UpdateMessages), 
                    sentBy, 
                    Encoding.UTF8.GetString(dataGram));
            }
        });
        _receiveThread.IsBackground = true;
        _receiveThread.Start();


        _sender = new UdpClient();
        _sender.JoinMulticastGroup(IPAddress.Parse(_multicastGroupAddress));
    }

    private void button1_Click(object sender, EventArgs e)
    {
        var data = Encoding.UTF8.GetBytes(textBox2.Text);
        _sender.Send(data, data.Length, new IPEndPoint(IPAddress.Broadcast, _port));
    }
}
Jeroen van Langen
  • 21,446
  • 3
  • 42
  • 57
  • Thank you - I had 2 calls out of order and one call using the specific IP address. Once I changed those it worked. – David Thielen Mar 30 '17 at 15:19
  • 1
    It doesn't, (copied from my existed code) Multicast groups are useful when multiple senders are used. And you want to 'split' the senders/receivers to groups. In this case, it was already in my code @Alophind – Jeroen van Langen Jun 12 '19 at 10:24