26

Problem: I am trying to bind a udp socket on a specific address. I will broadcast out a message. That same socket will need to be able to receive messages.

Current code:

static void Main()
{
    UdpClient Configuration = new UdpClient(new IPEndPoint(IPAddress.Parse(data.IPAddress), configuration.Port));  //set up the bind to the local IP address of my choosing
    ConfigurationServer.EnableBroadcast = true;
    Configuration.Connect(new IPEndpoint(IPAddress.Parse(data.BroadcastIP), configuration.Port);
    Listen();

 }

private void Listen()
{
    Task.Run(async () =>
            {
                while (true)
                {
                    var remoteIp = new IPEndPoint(IPAddress.Any, configuration.Port);
                    var data = await ConfigurationServer.ReceiveAsync();

                    // i would send based on what data i received here
                    int j = 32;
                }
            }
});
}   

I am not receiving data on listen thread. I know that the code on the other side is functional, and sending a directed UDP message to the IP/Port combo.

Jason
  • 2,147
  • 6
  • 32
  • 40
  • 7
    This question features code that does not work as intended (ala: There is an intended feature missing). It is therefore **off-topic** for CR. – Sumurai8 Nov 15 '16 at 18:22

1 Answers1

46

It can simply be done as

int PORT = 9876;
UdpClient udpClient = new UdpClient();
udpClient.Client.Bind(new IPEndPoint(IPAddress.Any, PORT));

var from = new IPEndPoint(0, 0);
var task = Task.Run(() =>
{
    while (true)
    {
        var recvBuffer = udpClient.Receive(ref from);
        Console.WriteLine(Encoding.UTF8.GetString(recvBuffer));
    }
});

var data = Encoding.UTF8.GetBytes("ABCD");
udpClient.Send(data, data.Length, "255.255.255.255", PORT);

task.Wait();
Vimes
  • 10,577
  • 17
  • 66
  • 86
L.B
  • 114,136
  • 19
  • 178
  • 224
  • what is 255.255.255.255 ? – Kiquenet Oct 19 '19 at 16:17
  • 2
    @Kiquenet it's the broadcast address on a network. Messages sent to the broadcast address will be sent to all devices on a network. https://en.wikipedia.org/wiki/Broadcast_address – Dan Gardner Sep 20 '20 at 17:22
  • this program exits immediately without waiting for a response – bturner1273 Dec 21 '20 at 21:15
  • @bturner1273 It is because it is a code snippet not a complete program. If you are writing a console app, add a blocking code at the end of your *Main* function like *Console.ReadLine* – L.B May 22 '21 at 20:12
  • Is there a reason why you placed the `var from = new IPEndPoint(0, 0);` outside the task? – Jeroen van Langen Jul 07 '22 at 07:11