简体   繁体   English

UDP 套接字不读取数据包

[英]UDP socket not reading packets

So I have a device connected to my network card and it sends data to port 11678 and address 192.168.121.1 using IPv4 and UDP.所以我有一个设备连接到我的网卡,它使用 IPv4 和 UDP 将数据发送到端口 11678 和地址 192.168.121.1。 I have checked that the device does actually send to that port and address using IPv4 and UDP by calling tcpdump.我已经通过调用 tcpdump 检查了设备确实使用 IPv4 和 UDP 发送到该端口和地址。 However my C socket does not receive any packets.但是我的 C 套接字没有收到任何数据包。 Below I have a minimum non-working example that just runs an infinite loop until one packet is received.下面我有一个最小的非工作示例,它只是运行一个无限循环,直到收到一个数据包。 It does not receive any packets even though tcpdump does, so I assume something is wrong with my code.即使 tcpdump 接收到任何数据包,它也不会收到任何数据包,所以我认为我的代码有问题。

#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>

#define DEST_ADDR "192.168.121.1"
#define DEST_PORT 11678
#define PACKET_MAXSIZE 1024

int main(int argc, char **argv) {
    struct sockaddr_in dest_addr;
    bzero(&dest_addr, sizeof(dest_addr));
    dest_addr.sin_family = AF_INET;

    /* create socket */
    int fd = socket(AF_INET, SOCK_DGRAM | SOCK_NONBLOCK, 0); // use SOCK_NONBLOCK?
    if (fd < 0) {
        perror("Could not create socket.");
    }

    /* bind port and address to socket */
    dest_addr.sin_port = htons(DEST_PORT);
    inet_aton(DEST_ADDR, &dest_addr.sin_addr);
    int rc = bind(fd, (struct sockaddr*) &dest_addr, sizeof(dest_addr));
    if (rc != 0) {
        perror("Could not bind socket to local address");
    }

    /* read packets */
    void* buf;
    posix_memalign(&buf, 4096, 1024);
    while (true) {
        ssize_t read_size = read(fd, buf, PACKET_MAXSIZE);
        printf("%d\n", read_size);
        if (read_size > 0) {
            break;
        }
    }

    return 0;
}

The read just returns -1 and sets errno to 11 ( EAGAIN ) in every iteration. read在每次迭代中只返回 -1 并将 errno 设置为 11 ( EAGAIN )。 Any help is appreciated.任何帮助表示赞赏。 Thanks in advance.提前致谢。

If you're on a system that uses iptables, check that you aren't dropping packets.如果您在使用 iptables 的系统上,请检查您是否没有丢弃数据包。 tcpdump will show packets that are incoming before they get to iptables. tcpdump 将在到达 iptables 之前显示传入的数据包。

Another thing is that you should be using epoll or select to read from the socket in a more controlled way.另一件事是您应该使用epollselect以更可控的方式从套接字读取。 EAGAIN isn't neccessarily wrong: it just means there's no data. EAGAIN 不一定是错误的:它只是意味着没有数据。 But you're whizzing round that while loop without waiting, so I'd expect lots of EAGAIN's until something actually arrives at the port.但是你在没有等待的情况下绕着那个while循环呼啸而过,所以我预计会有很多EAGAIN,直到有东西真正到达港口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM