UdpClient receive on broadcast address
Asked Answered
T

4

14

In c# I am using the UdpClient.Receive function:

public void StartUdpListener(Object state)
    {
        try
        {
            udpServer = new UdpClient(new IPEndPoint(IPAddress.Broadcast, 1234));
        }
        catch (SocketException ex)
        {
            MessageBox.Show(ex.ErrorCode.ToString());
        }

        IPEndPoint remoteEndPoint = null;
        receivedNotification=udpServer.Receive(ref remoteEndPoint);
        ...

However I am getting a socket exception saying that the address is not available with error code 10049 What do I do to negate this exception?

Thirsty answered 14/4, 2009 at 6:23 Comment(0)
I
24

Here's the jist of some code I am currently using in a production app that works (we've got a bit extra in there to handle the case where the client are server apps are running on a standalone installation). It's job is to receive udp notifications that messages are ready for processing. As mentioned by Adam Alexander your only problem is that you need to use IPAddress.Any, instead of IPAddress.Broadcast. You would only use IPAddress.Broadcast when you wanted to Send a broadcast UDP packet.

Set up the udp client

this.broadcastAddress = new IPEndPoint(IPAddress.Any, 1234);
this.udpClient = new UdpClient();
this.udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
this.udpClient.ExclusiveAddressUse = false; // only if you want to send/receive on same machine.

And to trigger the start of an async receive using a callback.

this.udpClient.Client.Bind(this.broadcastAddress);
this.udpClient.BeginReceive(new AsyncCallback(this.ReceiveCallback), null);

Hopefully this helps, you should be able to adapt it to working synchronously without too much issue. Very similar to what you are doing. If you're still getting the error after this then something else must be using the port that you are trying to listen on.

So, to clarify.

IPAddress.Any = Used to receive. I want to listen for a packet arriving on any IP Address. IPAddress.Broadcast = Used to send. I want to send a packet to anyone who is listening.

Impair answered 17/4, 2009 at 8:53 Comment(0)
S
5

for your purposes I believe you will want to use IPAddress.Any instead of IPAddress.Broadcast. Hope this helps!

Stovepipe answered 14/4, 2009 at 6:28 Comment(0)
C
0

That error means the protocol cant bind to the selected IP/port combination.

I havent used UDP broadcast in ages, but I do recall you need to use different IP ranges.

Claudicant answered 14/4, 2009 at 6:30 Comment(0)
D
0

There's nothing wrong with the way you have configured your UdpClient. Have you tried a different port number? Perhaps 1234 is already in use on your system by a different app.

Duncan answered 14/4, 2009 at 6:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.