在 C 中使用 UDP 通过套接字发送单个无符号字符

Sending a single unsigned char through a socket using UDP in C

我正在尝试通过缓冲区发送单个 unsigned char。我正在使用大小为 2

的缓冲区
unsigned char temp_buf [2];
temp_buf [0]= (unsigned char) 0xff;
temp_buf [1]= NULL;

我的 sendto 函数如下所示:

if (sendto(fd, temp_buf, sizeof (temp_buf), 0, (struct sockaddr *)&remaddr, addrlen) < 0)
        perror("sendto");

它编译没有问题,但是在 运行 时我得到一个错误:

sendto: Invalid argument

这意味着我使用的缓冲区有问题。我怀疑这个问题可能是因为我使用 siezeof 所以我将它更改为 strlen(temp_buf) 但仍然没有运气!

编辑:我试图通过不包括整个代码来使问题更简单,但在这里,很抱歉!

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <netdb.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include "port.h"

#define BUFSIZE 2048

int
main(int argc, char **argv)
{
    struct sockaddr_in myaddr;  /* our address */
    struct sockaddr_in remaddr; /* remote address */
    socklen_t addrlen = sizeof(remaddr);        /* length of addresses */
    int recvlen;            /* # bytes received */
    int fd;             /* our socket */
    int msgcnt = 0;         /* count # of messages we received */
    unsigned char buf[BUFSIZE]; /* receive buffer */


    /* create a UDP socket */

    if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
        perror("cannot create socket\n");
        return 0;
    }

    /* bind the socket to any valid IP address and a specific port */

    memset((char *)&myaddr, 0, sizeof(myaddr));
    myaddr.sin_family = AF_INET;
    myaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    myaddr.sin_port = htons(SERVICE_PORT);

    if (bind(fd, (struct sockaddr *)&myaddr, sizeof(myaddr)) < 0) {
        perror("bind failed");
        return 0;
    }

    /* now loop, receiving data and printing what we received */



        printf("waiting on port %d\n", SERVICE_PORT);

        //recvfrom(fd, buf, BUFSIZE, 0, (struct sockaddr *)&remaddr, &addrlen);

        //buf [0] = 0xff;
        unsigned char temp_buf [2];
        temp_buf [0]= (unsigned char) 0xff;
        temp_buf [1]= '[=12=]';

        if (sendto(fd, temp_buf, sizeof (temp_buf), 0, (struct sockaddr *)&remaddr, addrlen) < 0)
            perror("sendto");
        else
            printf("%s \n", "Communication established");



}

remaddr 的内容未初始化。换句话说,您没有告诉 sendto 将数据发送到哪里。

您需要使用要发送到的 IP 和端口填充此结构。

如果您取消注释对 recvfrom 的调用并随后从其他服务获取数据包,remaddr 将填充发送该数据包的 IP/port,然后您可以使用它发回一个数据包。但是没有那个,你需要填写remaddr.