c - 创建隧道时需要 "maxfd"做什么?

标签 c network-programming tcp tunnel

在此链接中,https://backreference.org/2010/03/26/tuntap-interface-tutorial/ ,有一个使用 tun/tap 接口(interface)创建 TCP 隧道的代码示例,如下所示。

  /* net_fd is the network file descriptor (to the peer), tap_fd is the
     descriptor connected to the tun/tap interface */

  /* use select() to handle two descriptors at once */
  maxfd = (tap_fd > net_fd)?tap_fd:net_fd;

  while(1) {
    int ret;
    fd_set rd_set;

    FD_ZERO(&rd_set);
    FD_SET(tap_fd, &rd_set); FD_SET(net_fd, &rd_set);

    ret = select(maxfd + 1, &rd_set, NULL, NULL, NULL);

    if (ret < 0 && errno == EINTR) {
      continue;
    }

    if (ret < 0) {
      perror("select()");
      exit(1);
    }

    if(FD_ISSET(tap_fd, &rd_set)) {
      /* data from tun/tap: just read it and write it to the network */

      nread = cread(tap_fd, buffer, BUFSIZE);

      /* write length + packet */
      plength = htons(nread);
      nwrite = cwrite(net_fd, (char *)&plength, sizeof(plength));
      nwrite = cwrite(net_fd, buffer, nread);
    }

    if(FD_ISSET(net_fd, &rd_set)) {
      /* data from the network: read it, and write it to the tun/tap interface.
       * We need to read the length first, and then the packet */

      /* Read length */
      nread = read_n(net_fd, (char *)&plength, sizeof(plength));

      /* read packet */
      nread = read_n(net_fd, buffer, ntohs(plength));

      /* now buffer[] contains a full packet or frame, write it into the tun/tap interface */
      nwrite = cwrite(tap_fd, buffer, nread);
    }
  }

该代码摘录中“maxfd”的用途是什么?确切的行是:

maxfd = (tap_fd > net_fd)?tap_fd:net_fd;

ret = select(maxfd + 1, &rd_set, NULL, NULL, NULL);

最佳答案

这是危险且过时的 select 函数工作方式的产物。它需要一个参数,该参数对传递给它的 fd_set 对象的大小(以位为单位)进行限制,并且不能使用大于 FD_SETSIZE 施加的任意限制的 fd 数字>。如果您未能满足这些要求,则会产生未定义的行为。

无论您在哪里看到 select,都应该将其替换为 poll,它不受这些限制,具有更易于使用的界面,并且具有更多功能。

关于c - 创建隧道时需要 "maxfd"做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53577163/

相关文章:

c - 声明为 const,但定义为非常量,C

c - 如何通过串行连接(蓝牙)获取 TCP/IP 数据包

java - 如何使客户端/服务器回合制java游戏可以在两台不同的计算机上玩

java - 是否有任何好的 API 可以维持 Flash <--> Java 之间的开放连接

windows-services - 如何知道哪个本地应用程序连接到我的套接字(Windows)

java - 为什么我通过 TCP 发送的文件包含的数据比它本身包含的文件多?

networking - 不可路由的 IP 地址

objective-c - 当 Apple 文档提到包含 ARC 属性的正确位置时,它是什么意思?

c++ - 为什么在遗留 strcpy() 中没有健全性检查

c - "Network programming"示例中的这段代码如何工作?