Socket in C: Proper way to close socket











up vote
2
down vote

favorite












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.










share|improve this question




























    up vote
    2
    down vote

    favorite












    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.










    share|improve this question


























      up vote
      2
      down vote

      favorite









      up vote
      2
      down vote

      favorite











      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.










      share|improve this question















      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.







      c sockets server






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited yesterday









      πάντα ῥεῖ

      71k970132




      71k970132










      asked yesterday









      Shin

      173




      173
























          3 Answers
          3






          active

          oldest

          votes

















          up vote
          3
          down vote



          accepted










          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.






          share|improve this answer




























            up vote
            4
            down vote













            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.






            share|improve this answer




























              up vote
              1
              down vote













              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.






              share|improve this answer





















                Your Answer






                StackExchange.ifUsing("editor", function () {
                StackExchange.using("externalEditor", function () {
                StackExchange.using("snippets", function () {
                StackExchange.snippets.init();
                });
                });
                }, "code-snippets");

                StackExchange.ready(function() {
                var channelOptions = {
                tags: "".split(" "),
                id: "1"
                };
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function() {
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled) {
                StackExchange.using("snippets", function() {
                createEditor();
                });
                }
                else {
                createEditor();
                }
                });

                function createEditor() {
                StackExchange.prepareEditor({
                heartbeatType: 'answer',
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader: {
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                },
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                });


                }
                });














                 

                draft saved


                draft discarded


















                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53237845%2fsocket-in-c-proper-way-to-close-socket%23new-answer', 'question_page');
                }
                );

                Post as a guest
































                3 Answers
                3






                active

                oldest

                votes








                3 Answers
                3






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes








                up vote
                3
                down vote



                accepted










                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.






                share|improve this answer

























                  up vote
                  3
                  down vote



                  accepted










                  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.






                  share|improve this answer























                    up vote
                    3
                    down vote



                    accepted







                    up vote
                    3
                    down vote



                    accepted






                    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.






                    share|improve this answer












                    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.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered yesterday









                    user803422

                    7772521




                    7772521
























                        up vote
                        4
                        down vote













                        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.






                        share|improve this answer

























                          up vote
                          4
                          down vote













                          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.






                          share|improve this answer























                            up vote
                            4
                            down vote










                            up vote
                            4
                            down vote









                            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.






                            share|improve this answer












                            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.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered yesterday









                            Steffen Ullrich

                            57.9k35395




                            57.9k35395






















                                up vote
                                1
                                down vote













                                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.






                                share|improve this answer

























                                  up vote
                                  1
                                  down vote













                                  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.






                                  share|improve this answer























                                    up vote
                                    1
                                    down vote










                                    up vote
                                    1
                                    down vote









                                    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.






                                    share|improve this answer












                                    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.







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered yesterday









                                    ulix

                                    135118




                                    135118






























                                         

                                        draft saved


                                        draft discarded



















































                                         


                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function () {
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53237845%2fsocket-in-c-proper-way-to-close-socket%23new-answer', 'question_page');
                                        }
                                        );

                                        Post as a guest




















































































                                        Popular posts from this blog

                                        Full-time equivalent

                                        さくらももこ

                                        13 indicted, 8 arrested in Calif. drug cartel investigation