我一直在尝试使用 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);
到:
int te = sendto(s, message, sizeof(message), 0, (struct sockaddr *) & si_other, slen);
另请注意,您不应使用 gets() , 因为它是 unsafe - 使用 fgets()反而。变化:
gets(message);
到:
fgets(message, sizeof(message), stdin);
关于C - 如何通过包含多个 0 字节的 UDP 发送字节字符数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28985637/