1
votes
int listen(int sockfd, int backlog);

Here is a description form linux man page

listen() marks the socket referred to by sockfd as a passive socket, that is, as a socket that will be used to accept incoming connection requests using accept(2).

The sockfd argument is a file descriptor that refers to a socket of type SOCK_STREAM or SOCK_SEQPACKET.

The backlog argument defines the maximum length to which the queue of pending connections for sockfd may grow. If a connection request arrives when the queue is full, the client may receive an error with an indication of ECONNREFUSED or, if the underlying protocol supports retransmission, the request may be ignored so that a later reattempt at connection succeeds.

The thing which bug me alot is why do we actually need to call listen.Is it to make the server start listening to the binded address and port.Isn't it the case that as soon as an address and port is binded to the socket descriptor the client can simply connect to that binded address.Thinks get more confusing when we don't make the listen call during the creation of an UDP server,does the UDP server automatically start listening as soon as an address is binded to it.

1

1 Answers

0
votes

A host can receive packets from anywhere at any time. With TCP, before you call listen the operating system responds to any arriving packet with an RST packet. After listen it will reply to SYN packets with a SYN-ACK packet, and adds information about the remote side to the list of pending "connections", and the connection is now established.

With UDP there are no connections. If an application is waiting for a UDP packet and one arrives, the operating system passes the packet to the app. If no one is expecting packets the OS drops them.

The bind function just gives an address for a socket. It's not limited for use in servers, you could use bind on client sockets as well to set the IP and port you connect from. It's usually not required, so you don't see it very often.