Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I have to close the socket on the server side after client disconnects?

Tags:

c

sockets

So let me simplify the code I'm working on:

int fd = socket(...);
int client = accept(fd, ...);
while (true) {
    int bytes_read = recv(client, ...);
    if (bytes_read == 0) {
        break;
    }
};

At this point I already know that the client is disconnected (recv returned 0). But do I still have to call

close(client);

?

like image 378
freakish Avatar asked Apr 12 '17 11:04

freakish


2 Answers

Yes.

When you recv() 0 bytes, that's the kernel's way of letting you know that the remote host has shut down their sending side of the connection. It's possible that they still have the socket open and could receive more data you send (but not reply).

When you call close() on a TCP socket, you are doing two things:

  1. Shutting down the local side of the socket, letting the remote host know that you're also finished transmitting. Without doing so, you potentially leave the clients hanging, waiting for you to send more data.
  2. Closing the file descriptor. This releases the entry in your process open file table. Without doing so, you are wasting resources and could find yourself out of memory or available file descriptors. Most every OS has a hard limit on the number of file descriptors (or handles) that a process can have open at one time.
like image 170
Jonathon Reinhart Avatar answered Sep 24 '22 02:09

Jonathon Reinhart


You need to close the descriptor to release the resources bound to it.

like image 37
Meixner Avatar answered Sep 27 '22 02:09

Meixner