c - 如何检查是否在 C Linux 中收到 UDP 数据包

标签 c linux sockets server udp

<分区>

下面示例代码中的“recvfrom()”等待直到接收到 UDP 数据包。

但是我需要检查UDP数据包是否可用。 如果没有收到数据包,则继续其他任务。 如果收到数据包,则接收数据包并解析。 我如何在 Linux c 程序中执行此操作?请帮忙!

for (;;) 
{
    printf("waiting on port %d\n", SERVICE_PORT);
    recvlen = recvfrom(fd, buf, BUFSIZE, 0, (struct sockaddr *)&remaddr, &addrlen);
    printf("received %d bytes\n", recvlen);
    if (recvlen > 0) {
        buf[recvlen] = 0;
        printf("received message: \"%s\"\n", buf);
    }
}

最佳答案

您可以使用 select函数来知道某个东西已准备好在套接字上读取。

while (1)
{
    int retval;
    fd_set rfds;
    // one second timeout
    struct timeval tv = {1,0};

    FD_ZERO(&rfds);
    FD_SET(fd, &rfds);

    retval = select(1, &rfds, NULL, NULL, &tv);

    if (retval == -1)
    {
        perror("select()");
        exit(1);
    }        
    else if (retval)
    {
        printf("Data is available now.\n");      
    }
    else
    {
        // no data to read... perform other tasks
    }
}

关于c - 如何检查是否在 C Linux 中收到 UDP 数据包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38071732/

相关文章:

c - 以网格形式绘制点

c - 如何使用 c 获取使用 dd 命令创建的文件的大小

linux - 在 Linux 机器上运行 Firefox 时“无法打开共享对象文件”

linux - 如何在 Ubuntu 中安装缓存存档

sockets - 设置高连接超时后套接字超时异常

c++ - 是否有 Pidgin 的替代品,但许可限制较少?

c - fread() 和 fwrite 在 C 编程中的工作原理

linux - LINUX bash 中的 typeset -l 和 typeset -u 是否等效?

c - 发送信号和 pselect?

javascript - 文件未通过 socket.io 发送