簡體   English   中英

創建隧道時對“ maxfd”有什么要求?

[英]What is the need for “maxfd” when creating a tunnel?

在此鏈接https://backreference.org/2010/03/26/tuntap-interface-tutorial/中 ,有一個使用tun / tap接口創建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 ,它不受這些限制,具有易於使用的界面並且具有更多功能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM