UDP recvfrom 数据显示不正确

UDP recvfrom data not displaying properly

Html 文件有以下内容

Helloworld.html

Hello World
Testing Echo Server

服务器输出

客户代码

//Pack contents into UDP packet and send
while(1) {
    //Check for Validity of File
    readSize = fread(buffer, 1, bufferSize, currentFile);
    if (readSize <= 0) {
        if (ferror(currentFile) != 0) {
            fprintf(stderr, "Unable to read from file %s\n", inputFile);
            free(buffer);
            fclose(currentFile);
            close(sDescriptor);
        }
        break;
    }
    //Send Data
    if (send(sDescriptor, buffer, readSize, 0) < 0) {
        fprintf(stderr,"Send failed\n");
        free(buffer);
        fclose(currentFile);
        close(sDescriptor);
        exit(1);
    }
}

服务器代码

/* Receive Data & Print */
unsigned int len = sizeof(cad);
int size = sizeof(buffer);
while (1) {
    charactersRead = recvfrom(sd, buffer, size, 0, (struct sockaddr *)&cad, &len);
    /* Print Address of Sender */
    printf("Got a datagram from %s port %d\n", inet_ntoa(cad.sin_addr), ntohs(cad.sin_port));
    printf("%s\n", buffer);
    if (charactersRead < 0 ) {
      perror("Error receiving data");
    } else {
      printf("GOT %d BYTES\n", charactersRead);
      /* Got something, just send it back */
      //sendto(sd, buffer, charactersRead, 0,(struct sockaddr *)&cad, &length);
    }
  }

如果需要更多信息,我愿意post。 客户端将文件内容作为 UDP 数据包发送,服务器接收并打印出来。但是,正如您所见,某些东西已损坏。我不知道为什么要这样做,如果我在 recvfrom 中切换第三个参数的参数,我会得到不同的输出。例如,如果我将尺寸变大,它实际上会打印出整个内容,但最后会出现损坏的字符。确定尺寸的正确方法是什么?那就是问题所在。 下面是当 size 参数变大时会发生什么。

这更接近预期,但仍然存在损坏位。

您在非空终止的缓冲区上使用 printf()。您收到的八个字节是 "Hello Wo",其余的不是损坏,只是缓冲区末尾后的内存中的内容。显示输出时需要使用字节数。

printf("%s\n", buffer);

应该是

printf("%.*s\n", charactersRead, buffer);

您忽略了计数。

如果 buffer 是一个指针,sizeof buffer 只会给你指针的大小,而不是它指向的内容的大小。