如何使用相同的 UDP 套接字发送和接收数据包?我在这段代码中缺少什么?

How can I use the same UDP socket both for sending and receiving packets? What am I missing in this code?

我正在尝试编写一个应用程序,其中客户端应将 UDP 数据包发送到服务器,然后服务器应通过无线接口回复客户端。客户端和服务器都在同一个二进制文件中实现,用户可以使用适当的命令行参数选择模式。

我正在使用 UDP,但在客户端和服务器通信时遇到了问题。 首先,在这两种情况下,我都尝试使用相同的 UDP 套接字来接收和发送数据包。我以为这是可能的,但我开始有些怀疑了。

那么,这是客户端和服务端的相关代码:

        struct sockaddr_in inaddr;

        fd=socket(AF_INET,SOCK_DGRAM,0);

        if(fd==-1) {
            perror("socket() error");
            exit(EXIT_FAILURE);
        }

        // Prepare sockaddr_in structure
        bzero(&inaddr,sizeof(inaddr));
        inaddr.sin_family=AF_INET;
        inaddr.sin_port=htons(opts.port); // opts.port is parsed from the command line
        inaddr.sin_addr.s_addr=opts.destIPaddr.s_addr; // opts.destIPaddr is parsed from the command line and already in the correct format

        // Bind to the wireless interface (devname is previusly obtained in a tested piece of code)
        if(setsockopt(sData.descriptor,SOL_SOCKET,SO_BINDTODEVICE,devname,strlen(devname))==-1) {
            perror("setsockopt() for SO_BINDTODEVICE error");
            close(sData.descriptor);
            exit(EXIT_FAILURE);
        }

两者都将使用以下方式读写:

sendto(fd,packet,packetsize,0,(struct sockaddr *)&(inaddr),sizeof(inaddr))

并且:

struct sockaddr_in srcAddr;
socklen_t srcAddrLen=sizeof(srcAddr);

// .....

recvfrom(fd,packet,MAX_PACKET_SIZE,0,(struct sockaddr *)&srcAddr,&srcAddrLen);

问题是客户端和服务器无法通信,客户端发送的每个数据包似乎总是收到一个 "port unreachable" ICMP 数据包(我可以清楚地看到,在 Wireshark 中,客户端发送正确的 UDP 数据包服务器用 "port unreachable").

拒绝了它们

可能我没有以正确的方式使用 UDP 套接字:你知道我在这里遗漏了什么吗?我的最终目标是:

虽然问题本身并不清楚,但您的评论似乎表明您没有 bind()ing 套接字的地址,正如@Someprogrammerdude 推断的那样。在这种情况下,重要的是要了解 bind()ing 与 SO_BINDTODEVICE 套接字选项所服务的目的不同,并且在很大程度上是正交的,尽管在选项名称中使用了 "BIND"。

bind()函数是关于将套接字与地址相关联,对于TCP和UDP,它包括一个端口号。 SO_BINDTODEVICE 是关于将套接字限制为通过特定设备传递的数据。虽然在实践中,IP地址和网络接口通常是一对一的映射关系,

  1. POSIX系统接口并不特定于IP协议族,它们注意避免假设地址族都具有与IP相似的特征。

  2. 即使是IP,一个网络接口也可以有多个地址。

  3. 特别是对于 IP,在任何情况下,您都需要将套接字与端口相关联,然后系统才会接受该端口的入站流量。 socket 选项不会这样做,它甚至不会直接将您的套接字与 IP 地址相关联。这就是bind().

  4. 的作用

在您提问的评论中

do I always need to use different struct sockaddr_in, one for bind and one for sendto? Can't I obtain the same result using only one structure?

您可以重用套接字地址结构,但请注意,bind()sendto() 的内容需要不同。前者需要一个 local 地址来绑定,而后者需要 remote 地址来发送消息。我认为为这些不同的目的使用单独的对象会更简洁一些,但这不是必需的。

至于让客户端选择自己的端口,正如我在评论中所说,这是UDP通常的操作方式。事实上,如果您还没有绑定套接字,那么在第一次调用 sendto()the system will take care of it for you 就很常见。您已经在使用 recvfrom(),服务器(以及客户端)可以通过它获取发送每条消息的对等方的地址。您应该能够将该地址对象反馈给 sendto() 以发送响应。因此,它应该像确保服务器 bind()s 以便收听众所周知的端口号一样简单,但客户端不会,以便使用系统自动分配的端口号。

我会亲自将 UDP 服务器绑定到通配符地址和特定端口,并使用 IP_PKTINFO 套接字选项获取接口和目标地址作为每个数据包的辅助消息。

本质上,启用 IP_PKTINFO 套接字选项意味着您收到 IPPROTO_IP 级别 IP_PKTINFO 类型 ancillary message with each packet you receive using recvmsg().

类似地,在发送响应时,您可以在辅助 IP_PKTINFO 消息中使用 ipi_ifindexipi_spec_dst 成员来告诉内核如何路由消息。

这样,您可以只绑定一个(或两个,如果您同时使用 IPv4 和 IPv6)通配符套接字,并使用它通过您想要的任何接口接收和发送 UDP 数据包;特别是,使用客户端用作目标的相同接口和源 IP 地址。每当新接口可用时,您的服务器端也会立即响应这些接口(尽管它显然可以根据它们来自的接口将不需要的客户端请求丢弃在地板上)。简单,而且相当健壮。

也许下面的例子server.c更好地说明了这一点:

#define _POSIX_C_SOURCE  200809L
#define _GNU_SOURCE
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/udp.h>
#include <net/if.h>
#include <netdb.h>
#include <signal.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>

static volatile sig_atomic_t  done = 0;

static void handle_done(int signum)
{
    if (!done)
        done = signum;
}

static int install_done(int signum)
{
    struct sigaction  act;

    memset(&act, 0, sizeof act);
    sigemptyset(&act.sa_mask);

    act.sa_handler = handle_done;
    act.sa_flags   = 0;

    return sigaction(signum, &act, NULL);
}

static inline const char *ip4_address(const struct in_addr addr)
{
    static char    buffer[32];
    char          *p = buffer + sizeof buffer;
    unsigned char  octet[4];

    /* in_addr is in network byte order. */
    memcpy(octet, &addr, 4);

    /* We build the string in reverse order. */
    *(--p) = '[=10=]';
    do {
        *(--p) = '0' + (octet[3] % 10);
        octet[3] /= 10;
    } while (octet[3]);
    *(--p) = '.';
    do {
        *(--p) = '0' + (octet[2] % 10);
        octet[2] /= 10;
    } while (octet[2]);
    *(--p) = '.';
    do {
        *(--p) = '0' + (octet[1] % 10);
        octet[1] /= 10;
    } while (octet[1]);
    *(--p) = '.';
    do {
        *(--p) = '0' + (octet[0] % 10);
        octet[0] /= 10;
    } while (octet[0]);

    return p;
}

int main(int argc, char *argv[])
{
    int   ip4fd, ip4port;
    char  dummy;

    if (argc < 2 || !strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) {
        fprintf(stderr, "\n");
        fprintf(stderr, "Usage: %s [ -h | --help ]\n", argv[0]);
        fprintf(stderr, "       %s UDP-PORT-NUMBER\n", argv[0]);
        fprintf(stderr, "\n");
        return EXIT_FAILURE;
    }
    if (sscanf(argv[1], " %d %c", &ip4port, &dummy) != 1 || ip4port < 1 || ip4port > 65535) {
        fprintf(stderr, "%s: Invalid UDP port number.\n", argv[1]);
        return EXIT_FAILURE;
    }

    if (install_done(SIGHUP) ||
        install_done(SIGINT) ||
        install_done(SIGTERM)) {
        fprintf(stderr, "Cannot install signal handlers: %s.\n", strerror(errno));
        return EXIT_FAILURE;
    }

    ip4fd = socket(AF_INET, SOCK_DGRAM, 0);
    if (ip4fd == -1) {
        fprintf(stderr, "Cannot create an UDP socket: %s.\n", strerror(errno));
        return EXIT_FAILURE;
    }

    /* Set the IP_PKTINFO socket option, so each received datagram has an
       ancillary message containing a struct in_pktinfo. */
    {
        int  option = 1;
        if (setsockopt(ip4fd, IPPROTO_IP, IP_PKTINFO, &option, sizeof option) == -1) {
            fprintf(stderr, "Cannot set IP_PKTINFO socket option: %s.\n", strerror(errno));
            close(ip4fd);
            return EXIT_FAILURE;
        }
    }

    /* Bind to the wildcard address, to receive packets using any network interface. */
    {
        struct sockaddr_in  ip4addr;

        ip4addr.sin_family = AF_INET;
        ip4addr.sin_port   = htons(ip4port);
        ip4addr.sin_addr.s_addr = htonl(INADDR_ANY);

        if (bind(ip4fd, (const struct sockaddr *)(&ip4addr), sizeof ip4addr) == -1) {
            fprintf(stderr, "Cannot bind to port %d: %s.\n", ip4port, strerror(errno));
            close(ip4fd);
            return EXIT_FAILURE;
        }
    }

    printf("Now listening on UDP port %d.\n", ip4port);
    printf("Press CTRL+C, or send HUP, INT, or TERM (pid %ld) to exit.\n",
           (long)getpid());
    fflush(stdout);

    /* Receive UDP messages, and describe them. */
    {
        unsigned char        payload[4096], ancillary[1024];
        char                *iface, ifacebuf[IF_NAMESIZE + 1];
        unsigned int         iface_index;
        struct in_addr       iface_addr, dest_addr;
        struct iovec         iov;
        struct msghdr        hdr;
        struct cmsghdr      *cmsg;
        struct sockaddr_in   from;
        struct in_pktinfo   *info;
        ssize_t              len;
        size_t               i;

        while (!done) {

            iov.iov_base = payload;
            iov.iov_len = sizeof payload;

            hdr.msg_name = &from;
            hdr.msg_namelen = sizeof from;

            hdr.msg_iov = &iov;
            hdr.msg_iovlen = 1;

            hdr.msg_control = ancillary;
            hdr.msg_controllen = sizeof ancillary;

            hdr.msg_flags = 0;

            /* Receive a new datagram. */
            len = recvmsg(ip4fd, &hdr, 0);
            if (len < 0) {
                if (len == -1) {
                    if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)
                        continue;
                    fprintf(stderr, "Error receiving data: %s.\n", strerror(errno));
                } else
                    fprintf(stderr, "recvmsg() error: Unexpected return value, %zd.\n", len);
                close(ip4fd);
                return EXIT_FAILURE;
            }

            /* Report. */
            printf("Received %zu bytes from %s port %d:\n",
                   (size_t)len, ip4_address(from.sin_addr), ntohs(from.sin_port));

            /* Check the ancillary data for the pktinfo structure. */
            info = NULL;
            for (cmsg = CMSG_FIRSTHDR(&hdr); cmsg != NULL; cmsg = CMSG_NXTHDR(&hdr, cmsg))
                if (cmsg->cmsg_level == IPPROTO_IP && cmsg->cmsg_type == IP_PKTINFO)
                    info = (void *)CMSG_DATA(cmsg);

            if (!info) {
                fprintf(stderr, "Error: Packet is missing the IP_PKTINFO ancillary information!\n");
                close(ip4fd);
                exit(EXIT_FAILURE);
            }

            /* info may be unaligned. */
            memcpy(&iface_index, &(info->ipi_ifindex),   sizeof info->ipi_ifindex);
            memcpy(&iface_addr,  &(info->ipi_spec_dst),  sizeof info->ipi_spec_dst);
            memcpy(&dest_addr,   &(info->ipi_addr),      sizeof info->ipi_addr);

            iface = if_indextoname(info->ipi_ifindex, ifacebuf);

            /* Report the IP_PKTINFO information. */
            if (iface)
                printf("  Interface: %u (%s)\n", iface_index, iface);
            else
                printf("  Interface: %u\n", iface_index);
            printf("  Local address: %s port %d\n", ip4_address(iface_addr), ip4port);
            printf("  Real destination: %s port %d\n", ip4_address(dest_addr), ip4port);

            for (i = 0; i < (size_t)len; i++) {
                if (i == 0)
                    printf("  Data: 0x%02x", payload[i]);
                else
                if ((i & 15) == 0)
                    printf("\n        0x%02x", payload[i]);
                else
                    printf(" 0x%02x", payload[i]);
            }

            if (len > 0)
                printf("\n");

            fflush(stdout);

            /*
             * Construct a response.
             */
            payload[0] = 'O';
            payload[1] = 'k';
            payload[2] = '!';
            payload[3] = '\n';
            iov.iov_base = payload;
            iov.iov_len = 4;

            /* Keep hdr.msg_name and hdr.msg_namelen intact. */

            hdr.msg_iov = &iov;
            hdr.msg_iovlen = 1;

            /* Prep the ancillary data. */
            hdr.msg_control = ancillary;
            hdr.msg_controllen = CMSG_SPACE(sizeof (struct in_pktinfo));

            cmsg = CMSG_FIRSTHDR(&hdr);
            cmsg->cmsg_level = IPPROTO_IP;
            cmsg->cmsg_type = IP_PKTINFO;
            cmsg->cmsg_len = CMSG_LEN(sizeof (struct in_pktinfo));
            info = (void *)CMSG_DATA(cmsg);
            /* info may be unaligned. */
            memcpy(&(info->ipi_ifindex), &iface_index, sizeof info->ipi_ifindex);
            memcpy(&(info->ipi_spec_dst), &iface_addr, sizeof info->ipi_spec_dst);
            memcpy(&(info->ipi_addr), &from.sin_addr,  sizeof info->ipi_addr);

            hdr.msg_flags = 0;

            /* Send the response. */
            do {
                len = sendmsg(ip4fd, &hdr, MSG_NOSIGNAL);
            } while (len == -1 && errno == EINTR);
            if (len == -1) {
                fprintf(stderr, "Cannot send a response message: %s.\n", strerror(errno));
                close(ip4fd);
                return EXIT_FAILURE;
            }

            printf("  %zd-byte response sent successfully.\n", len);
            fflush(stdout);
        }
    }

    close(ip4fd);
    return EXIT_SUCCESS;
}

使用例如编译gcc -Wall -O2 server.c -o server 和 运行 将端口号指定为命令行参数。例如,./server 4044.

为了测试,我在客户端使用了 netcat:echo 'Hello!' | nc -q 1 -u theipaddress 4044

因为我写这篇文章的时候已经是周五深夜了,而且我也懒得设置一些额外的设备,所以我只在一台机器上进行了非常轻微的测试。逻辑是合理的;只有我的实现可能会关闭。

如果您有任何疑问或发现错误或明显错误,请在评论中告诉我,以便我进行验证和修复。