Aaron
Aaron

Reputation: 1208

UDP recvfrom data not displaying properly

Html file has the following content

Helloworld.html

Hello World
Testing Echo Server

Output from Server

enter image description here

Client Code

//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);
    }
}

Server Code

/* 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);
    }
  }

Any more information needed, I will be willing to post. The client will send the contents of a file as a UDP packet and the server receives it and prints it out. However, as you can something is corrupted. I have no idea why this is doing this, If I switch the parameters of the third argument in recvfrom i get different outputs. For example, If i make the size larger it will actually print out the whole thing, but with corrupted chars at the end. What is the correct way of determining the size? That's if that's the problem. Here's what happens when the size argument is made larger. enter image description here

This is closer to what is expected, but still corrupt bits are there.

Upvotes: 0

Views: 1107

Answers (2)

user207421
user207421

Reputation: 311050

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

That should be

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

You're ignoring the count.

And if buffer is a pointer, sizeof buffer is only going to give you the size of the pointer, not the size of what it points to.

Upvotes: 2

janm
janm

Reputation: 18359

You are using printf() on a buffer that is not null terminated. The eight bytes you received are "Hello Wo", the rest is not corruption, just stuff in memory past the end of your buffer. You need to use the byte count when displaying your output.

Upvotes: 5

Related Questions