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

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

正如您在上面定义的数组中看到的,我在位置 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/

相关文章:

c - 我的 C 代码有什么问题(C 初学者)

c - 简单 Mac OSX C 程序中的总线错误

java - Java 中的 IPv6 可用性

c++ - 如何向客户端重播 TCP 流

networking - 证明网络确实不可用

sockets - 如何将 UDP 套接字绑定(bind)到一系列端口

c - 为什么 ptrdiff_t 在 i > j 时返回一个与 i - j 的正差数字,而在 i < j 时返回一个不相关的大数

c - 同时对两个数组进行并行数组快速排序

c++ - UDP 数据包传输和 C++

c - 在 C 程序中查找 UDP 数据有效负载中的八位字节