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

时间:2015-03-11 11:37:32

标签: 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,
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;

正如您在上面定义的数组中看到的那样,我在地方有一个0x00字节5. Sendto只发送前4个字节。

1 个答案:

答案 0 :(得分:1)

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

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

为:

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

另请注意,您不应该使用gets(),因为它是unsafe - 而是使用fgets()。变化:

gets(message);

为:

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