Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket in C: Proper way to close socket

Tags:

c

server

sockets

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.

like image 905
Shin Avatar asked Mar 18 '26 19:03

Shin


2 Answers

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.

like image 162
user803422 Avatar answered Mar 21 '26 07:03

user803422


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.

like image 32
Steffen Ullrich Avatar answered Mar 21 '26 08:03

Steffen Ullrich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!