簡體   English   中英

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

它編譯沒有問題,但是在運行時我收到一個錯誤:

發送到:無效的參數

這意味着我使用的緩沖區有問題。 我懷疑這個問題可能是因為我使用了 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]= '\0';

        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/端口,然后您可以使用它來發送數據包。 但沒有那個,你需要填寫remaddr

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM