Shin
Shin

Reputation: 37

Socket in C: Proper way to close socket

I often see sample codes for a server program using socket.

(For simplicity, here I don't check return values of functions such as socket() or bind() etc.)

int sockfd = 0, newsockfd = 0;
struct sockaddr_in address;

sockfd = socket(AF_INET, SOCK_STREAM, 0);

bind(sockfd, (struct sockaddr*)&address, sizeof(address));
listen(sockfd, 1);

newsockfd = accept(sockfd, (struct sockaddr*)NULL, NULL);

... do some communication ...

close(newsockfd);

Most of sample codes I found on the web have close(newsockfd) but don't have close(sockfd). My question is whether it is really correct NOT to close sockfd.

If it's correct, I want to know why. My understanding is that sockfd is one of the file descriptors and it seems to have no reason to quit program without closing it.

More specifically, I'm wondering that not-closing-sockfd can cause the bind error (e.g. this socket is aready in use...) when the program works next time.

I really appreciate if you help me. Thank you for your time.

Upvotes: 3

Views: 12458

Answers (3)

ulix
ulix

Reputation: 373

sockfd act as a server socket: it is used only to accept more and more incoming connections. You keep sockfd opened, bound and listening as long as you have to accept and handle new connections on newsockfd, wich hold the current connection on wich you are reading/writing from/to some peer program. When done with newsockfd you close it and, if requiref, accept a new one with accept() on sockfd. And so on.

Upvotes: 1

user803422
user803422

Reputation: 2814

You should always close sockfd when you stop the listening.

Two reasons why some developers do not care very much about not closing sockfd:

  • If your program quits without closing it, the OS will close sockfd for you
  • Most of the time, servers keep the listening open all the time (eg: for months)

However if your program launches a listening socket on some event, then closes it after a while, and loops, then you must close the sockfd, to prevent an error EADDRINUSE (Address already in use) at next iteration, and a memory leak.

Besides, the error EADDRINUSE (Address already in use) may occur on other circumstances that I do not detail here.

Upvotes: 4

Steffen Ullrich
Steffen Ullrich

Reputation: 123320

Resources allocated by the application, like memory or open file descriptors (which includes sockets) will be automatically freed by modern OS if the program exits. Thus, if the server socket should be available throughout the whole program (in order to accept connections) it is fine to not explicitly close it but let the OS do this when the application exits.

Upvotes: 4

Related Questions