Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UDP Bind Method

I am trying to set up a UDP communication link between 2 computers. One computer is running the client app and the other is running the server app. The client app gives the error:

You must call the Bind method before performing this operation.

Here is my code below for the client below and I have commented where the error occurs:

 public delegate void ShowMessage(string message);
    UdpClient udpClient = new UdpClient();
    Int32 port = 11000;
    public ShowMessage myDelegate;
    Thread thread;


private void Form1_Load(object sender, EventArgs e)
    {
        thread = new Thread(new ThreadStart(ReceiveMessage));
        thread.IsBackground = true;
        thread.Start();
    }


    private void ReceiveMessage()
    {
        while (true)
        {
            IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, port);

            //Error on this line
            byte[] content = udpClient.Receive(ref remoteIPEndPoint);

            if (content.Length > 0)
            {
                string message = Encoding.ASCII.GetString(content);


                this.Invoke(myDelegate, new object[] { message });
            }

        }

    }

Any help would be greatly appreciated.

source -> http://lamahashim.blogspot.com/2009/06/using-c-udpclient-send-and-receive.html

like image 363
user112016322 Avatar asked Jul 27 '12 14:07

user112016322


People also ask

How do I bind a UDP socket to an IP address?

You would do this with the bind() function: int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen); The first parameter is the file descriptor for the socket. The second is a pointer to a socket address structure which contains (for IPv4 or IPv6) the IP address and port to bind to.

What does bind do in socket?

The bind() function binds a unique local name to the socket with descriptor socket. After calling socket(), a descriptor does not have a name associated with it. However, it does belong to a particular address family as specified when socket() is called.


2 Answers

I believe you need to call Bind on the listening server first:

udpServer.Client.Bind(new IPEndPoint(IPAddress.Any, 11000));
like image 50
Adi Lester Avatar answered Oct 03 '22 23:10

Adi Lester


You need to tell the udpclient what port to listen to. The IPEndpoint you pass the receive method can be set to anything you like, since it gets populated with the senders details. It does not direct the udpclient to listen to port 11000. In affect you're trying to listen to port 0, which instructs the udpclient to pick it's own port.

Have a look at http://msdn.microsoft.com/en-us/library/system.net.sockets.udpclient.receive.aspx

You'll see the constructor is called with the port to listen on.

like image 32
Simon Halsey Avatar answered Oct 03 '22 21:10

Simon Halsey