C 如何通过UDP发送包含多个0字节的字节字符数组?

C 如何通过UDP发送包含多个0字节的字节字符数组?,c,networking,udp,sendto,C,Networking,Udp,Sendto,我一直在尝试使用sendto()命令通过UDP将自定义帧发送到另一台PC。工作正常,但只要阵列中有0字节,它就会(当然)将其识别为\0值并停止在该字节处。我怎样才能绕过它,然后通过网络发送一个0字节(0x00) char buffer[26] = {0x06, 0x10, 0x02, 0x05, 0x00, 0x1a, 0x08, 0x01, 0xc0, 0xa8, 0x7e, 0x80, 0x0e, 0x58, 0x08, 0x01, 0xc0, 0xa8, 0x7e, 0x80, 0x0e,

我一直在尝试使用sendto()命令通过UDP将自定义帧发送到另一台PC。工作正常,但只要阵列中有0字节,它就会(当然)将其识别为\0值并停止在该字节处。我怎样才能绕过它,然后通过网络发送一个0字节(0x00)

char buffer[26] = {0x06, 0x10, 0x02,
0x05, 0x00, 0x1a, 0x08, 0x01, 0xc0,
0xa8, 0x7e, 0x80, 0x0e, 0x58, 0x08,
0x01, 0xc0, 0xa8, 0x7e, 0x80, 0x0e,
0x58, 0x04, 0x04, 0x02, 0x00};

printf("Enter port # to listen to: \n");
int PORT;
scanf("%d", &PORT);
printf("Enter IP Address to send to: \n");
char SERVER[20];
scanf("%s", SERVER);

struct sockaddr_in si_other;
int s, slen=sizeof(si_other);
char buf[26];
char message[26];
if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
    die ("socket()");
}

memset((char *) &si_other, 0, sizeof(si_other));
si_other.sin_family = AF_INET;
si_other.sin_port = htons(PORT);

if (inet_aton(SERVER, &si_other.sin_addr) == 0) {
    fprintf(stderr, "inet_aton() failed\n");
    exit(1);
}

while(1) {
    printf("Enter message: ");
    gets(message);
    memcpy(message, buffer, 26);

    int te = sendto(s, message, strlen(message), 0,     (struct sockaddr *) & si_other, slen);
    //Send message
    if ( te == -1) {
        die("sendto()");
    }

    //Receive reply and print
    memset(buf,'\0', BUFLEN);

    //Receive Data, blocking
    if(recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) & si_other, & slen) == -1) {
        die("receive()");
    }
    puts(buf);
}

close(s);
return 0;
正如您在上面定义的数组中看到的,我在第5处有一个0x00字节。Sendto将只发送前4个字节。

如果字符串包含有效的
'\0'
字符,请不要使用
strlen()。我建议你改变:

int te = sendto(s, message, strlen(message), 0, (struct sockaddr *) & si_other, slen);
致:

还要注意的是,您不应该使用,因为它是-use。更改:

gets(message);
致:

gets(message);
fgets(message, sizeof(message), stdin);