Question

Is it necessary to have in the client bind, if I want to receive data from a server?

I've seen a schema (look at the image below), and it seems that it's not necessary. But from what I know, bind is necessary to give an address to a socket. If I don't "bind" the socket, how can I send data to it?

UDP client/server

Was it helpful?

Solution 2

As a client, the application needs to be aware of the server port to which it needs to connect, and as a server, the application needs to be aware of the server port to which it needs to listen. Therefore, the server needs to bind to an IP address and port so that the client can connect to it.

The client can simply create a socket and call connect(). Binding to an available IP address and ephemeral port shall implicitly happen. But, yes, nothing prevents you from having the client bind to a particular IP address and port.

In the case of UDP, despite there being no "connection" mechanism, servers still need to bind to IP addresses and ports to allow the clients to send data to them.

OTHER TIPS

A call to bind() only binds a socket to a port. Hence, in this case, it is required for a server to bind to a port.

A client, on the other hand, just needs to send to or receive data from a specific port (server); hence, it just connect()s and then does a recvfrom() and sendto().

Read last paragraph of section 5.3: http://beej.us/guide/bgnet/output/html/singlepage/bgnet.html

On most systems, if you call sendto with a UDP socket that has not been bound, it implicitly binds it to INADDR_ANY and some currently unused port, so if that's what you want (which is the common case), there is no need for an explicit bind on the client.

On some systems, trying to send with a unbound udp socket will give you a 'socket not bound' error, so if you want maximum portability, you should bind the client socket (to INADDR_ANY with port 0 to pick any currently unused port) before you try to send.

You either need to bind and then you can sendto(fd,data,destination) + recvfrom(fd), or you can just connect the socket and use send(fd,data) (without destination) and recv(fd). The connect will do an implicit binding by using a more or less random port number and an local IP suitable for reaching the given target.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top