为什么客户端不关闭套接字?

时间:2019-01-05 15:16:03

标签: c linux sockets

我正在从https://github.com/hayatoito/apue-2e/blob/master/sockets/ruptime.c的APUE读取套接字客户端示例。 我找不到它关闭或关闭其套接字。总的来说,客户端不必关闭其套接字文件描述符是否正确? 客户端什么时候需要关闭其套接字文件描述符,什么时候不需要?

为了进行比较,其服务器在最后关闭了套接字:https://github.com/hayatoito/apue-2e/blob/master/sockets/ruptimed.c

谢谢。

客户:

#include "apue.h"
#include <netdb.h>
#include <errno.h>
#include <sys/socket.h>

#define MAXADDRLEN  256
#define BUFLEN      128

extern int connect_retry(int, const struct sockaddr *, socklen_t);

void
print_uptime(int sockfd)
{
    int n;
    char buf[BUFLEN];

    while ((n = recv(sockfd, buf, BUFLEN, 0)) > 0)
        write(STDOUT_FILENO, buf, n);
    if (n < 0)
        err_sys("recv error");
}

int
main(int argc, char *argv[])
{
    struct addrinfo *ailist, *aip;
    struct addrinfo hint;
    int sockfd, err;

    if (argc != 2)
        err_quit("usage: ruptime hostname");
    hint.ai_flags = 0;
    hint.ai_family = 0;
    hint.ai_socktype = SOCK_STREAM;
    hint.ai_protocol = 0;
    hint.ai_addrlen = 0;
    hint.ai_canonname = NULL;
    hint.ai_addr = NULL;
    hint.ai_next = NULL;
    if ((err = getaddrinfo(argv[1], "ruptime", &hint, &ailist)) != 0)
        err_quit("getaddrinfo error: %s", gai_strerror(err));
    for (aip = ailist; aip != NULL; aip = aip->ai_next) {
        if ((sockfd = socket(aip->ai_family, SOCK_STREAM, 0)) < 0)
            err = errno;
        if (connect_retry(sockfd, aip->ai_addr, aip->ai_addrlen) < 0) {
            err = errno;
        } else {
            print_uptime(sockfd);
            exit(0);
        }
    }
    fprintf(stderr, "can't connect to %s: %s\n", argv[1], strerror(err));
    exit(1);
}

服务器:

#include "apue.h"
#include <netdb.h>
#include <errno.h>
#include <syslog.h>
#include <sys/socket.h>

#define BUFLEN  128
#define QLEN 10

#ifndef HOST_NAME_MAX
#define HOST_NAME_MAX 256
#endif

extern int initserver(int, struct sockaddr *, socklen_t, int);

void
serve(int sockfd)
{
    int clfd;
    FILE *fp;
    char buf[BUFLEN];

    for (;;) {
        clfd = accept(sockfd, NULL, NULL);
        if (clfd < 0) {
            syslog(LOG_ERR, "ruptimed: accept error: %s", strerror(errno));
            exit(1);
        }
        if ((fp = popen("/usr/bin/uptime", "r")) == NULL) {
            sprintf(buf, "error: %s\n", strerror(errno));
            send(clfd, buf, strlen(buf), 0);
        } else {
            while (fgets(buf, BUFLEN, fp) != NULL)
                send(clfd, buf, strlen(buf), 0);
            pclose(fp);
        }
        close(clfd);
    }
}

int
main(int argc, char *argv[])
{
    struct addrinfo *ailist, *aip;
    struct addrinfo hint;
    int sockfd, err, n;
    char *host;

    if (argc != 1)
        err_quit("usage: ruptimed");
#ifdef _SC_HOST_NAME_MAX
    n = sysconf(_SC_HOST_NAME_MAX);
    if (n < 0)                  /* best guess */
#endif
        n = HOST_NAME_MAX;
    host = malloc(n);
    if (host == NULL)
        err_sys("malloc error");
    if (gethostname(host, n) < 0)
        err_sys("gethostname error");
    daemonize("ruptimed");
    hint.ai_flags = AI_CANONNAME;
    hint.ai_family = 0;
    hint.ai_socktype = SOCK_STREAM;
    hint.ai_protocol = 0;
    hint.ai_addrlen = 0;
    hint.ai_canonname = NULL;
    hint.ai_addr = NULL;
    hint.ai_next = NULL;
    if ((err = getaddrinfo(host, "ruptime", &hint, &ailist)) != 0) {
        syslog(LOG_ERR, "ruptimed: getaddrinfo error: %s",
               gai_strerror(err));
        exit(1);
    }
    for (aip = ailist; aip != NULL; aip = aip->ai_next) {
        if ((sockfd = initserver(SOCK_STREAM, aip->ai_addr,
                                 aip->ai_addrlen, QLEN)) >= 0) {
            serve(sockfd);
            exit(0);
        }
    }
    exit(1);
}

2 个答案:

答案 0 :(得分:3)

  

一般来说,客户端不必关闭其套接字文件描述符是真的吗?

不,这不是真的。

这种信念的变体在早期的Microsoft Internet Explorer浏览器(版本1至5)中导致了许多keepalive问题,必须在服务器端解决该问题。 (从本质上讲,操作系统无法确保适当的完整TCP connection termination。)

但是,如果进程将要退出,则不关闭所有套接字并不是一个错误,因为POSIX.1(定义此功能的标准和此处使用的C接口)明确表示(例如,{{3 }}),当进程退出时,所有打开的流都将关闭。从理论上讲,这与动态内存分配类似:进程退出时,无需free()所有动态分配的内存,因为当进程退出时,所有(非共享)动态分配的内存都会自动释放退出。

实际上,显式关闭所有套接字描述符要更健壮。对于TCP连接,尤其如此,因为连接终止涉及FIN和ACK数据包交换。尽管人们可以相信操作系统始终能够正确完成工作,但MSIE的示例表明,现实的可信度要差得多,而彻底的获取可以带来更好的用户体验。

  

客户端何时需要关闭其套接字文件描述符,什么时候不需要?

实践中有两种情况:

  1. 连接终止时。

    描述符是一种有限的资源,一旦不再需要描述符就将其关闭,以确保不会浪费资源。确实没有充分的理由将套接字连接保持打开所需的时间。某些事情(例如,使用exit()遍历文件系统层次结构)在可以使用大量描述符的情况下效率更高,因此,由于程序员的懒惰,小心处理过程不会耗尽它们是一个好主意。

  2. 通过fork()创建子进程时,该子进程不应访问该套接字连接。

    当前的Linux,MacOS,FreeBSD和OpenBSD至少支持“执行时关闭”标志(通常通过fcntl(sfd, F_SETFD, FD_CLOEXEC))。在Linux中,您可以使用nftw()创建执行时关闭套接字描述符,并使用socket(domain, type | SOCK_CLOEXEC, protocol)创建套接字对。

    成功执行socketpair(domain, type | SOCK_CLOEXEC, protocol, sfd)调用后,将关闭执行时关闭描述符,并用正在执行的任何操作替换该进程。因此,如果在分叉后接exec或_Exit,并且所有套接字描述符都是close-on-exec,则重复的套接字会“自动”关闭,而您不必担心。

    请注意,如果您的代码使用popen(),则最好将套接字描述符设为close-on-exec,否则您运行的命令可能可以访问连接。可惜在目前这个时间点(2019年初),这是完全不规范的。

    还请注意,如果子进程不执行另一个二进制文件,但是例如放弃特权(对客户端来说是罕见的),则执行时close-on-exec将不会执行任何操作。因此,关闭(在子进程中)显式“手工”关闭套接字描述符的不必要重复对于正确进行权限分离仍然很重要。但这很少是客户端应用程序的问题,更多的是服务等问题。

换句话说,每当您希望终止套接字连接时,或者当套接字连接有多余的副本时,请close()

答案 1 :(得分:2)

始终必须关闭套接字,否则它将泄漏资源。

有很多方法可以关闭它,但是在关闭之前,请确保套接字数据为空。因此,您必须在关闭后调用关闭程序。

相关问题