4
votes

In a Socket communication when a server accepts a connection, it returns a value which is always greater than 0 if the connection is successful.

 ConnectedSocket = accept(sock_desc, (struct sockaddr *)&echoClntAddr,(socklen_t*)&clntSock);

Consider a client connected to the server and a server with the number 1 assigned. Then the client gets disconnected, and after some time another client connects. Will the accept function assign it the number 1 or number 2?

If the accept function will assign number 2, then after how many connections will number 1 be assigned again?

2
accept() might very well also return 0. - alk
Why are you concerned about accept return value uniqueness? - zoska

2 Answers

4
votes

The accept call returns a file descriptor which will be used for the new connection. From the man page of accept:

On success, these system calls return a nonnegative integer that is a descriptor for the accepted socket. On error, -1 is returned, and errno is set appropriately

The accept will never return 1 since it's the file descriptor used for standard output (unless you close this file descriptor programmatically!). As for the second question:

If accept function will assign number 2 then after how many connections will number 1 again be assigned ?

accept will use the first unused file descriptor in the process table. Thus, it's possible to reuse the same "returned number" (file descriptor) as soon as the related TCP connection has been closed.

1
votes

If I understood your question correctly you ask about uniqueness of integers returned from accept. accept returns file descriptor so if we are talking about POSIX OS then POSIX requires:

The open() function shall return a file descriptor for the named file that is the lowest file descriptor not currently open for that process.

accept internally calls get_unused_fd_flags which calls __alloc_fd to generate new file descriptor, open generates FD the same way so everything that applies to open regarding FDs applies to accept.

So conclusion: file descriptors can be reused and accept can return repeated numbers if those file descriptors were closed earlier.