【问题标题】:Reading Data From UDP socket从 UDP 套接字读取数据
【发布时间】:2024-01-21 21:22:02
【问题描述】:

我使用以下函数从文件描述符中读取...

int cread(int fd, char *buf, int n){

  int nread;

  if((nread=read(fd, buf, n))<0){
    perror("Reading data");
    exit(1);
  }
  return nread;
}

以下是使用上述函数的函数

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);

  tap2net++;
  do_debug("TAP2NET %lu: Read %d bytes from the tap interface\n", tap2net, nread);

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

  do_debug("TAP2NET %lu: Written %d bytes to the network\n", tap2net, nwrite);
}

它们都适用于 TCP siocket,但不适用于 udp 套接字。任何帮助将不胜感激

【问题讨论】:

  • tap_fd 是否在为 UDP 案例设置的文件描述符中?

标签: networking udp tcp


【解决方案1】:

不清楚您的问题到底是什么,但如果net_fd 是一个UDP 套接字,那么两个cwrite() 调用将创建两个 UDP 数据报。

在大小前面加上 UDP 并没有什么意义 - UDP 会为您维护消息边界。因此,在 UDP 情况下,只需完全删除 plength 部分即可。

【讨论】: