0

I am having a problem with the following. In particular, I am trying to extract a uint32_t and a char* from the buffer argument passed into the recvfrom() method. At this point, the integer can be extracted properly using the following code:

recvfrom(s, buf, buffer_size, 0, (struct sockaddr*)&si_other, &slen);

uint32_t recv_int = ntohl(*(int*)buf);

char* recv_char = (char*)malloc(6); // NOTE: The original string was "Hello", which has 6 bytes.
strcpy(recv_char, ((char*)buf + sizeof(uint32_t)));

printf("The returned values are %d %s\n", recv_int, recv_char);

However, when I perform printf as shown above, only recv_int has a value. recv_char is a blank string. However, I originally stored "Hello" in the buffer and hence, "Hello" should be printed to stdout.

EDIT:

This is the code that was being used in sendto():

uint32_t my_int = 3;
char* sendString = "Hello";
char* buffer = (char*)malloc(strlen(sendString) + sizeof(int));
memcpy(buffer, &my_int, sizeof(int));
strcpy((char*)buffer + sizeof(int), sendString);

if (sendto(s, buffer, sizeof(int) + strlen(sendString), 0, (struct sockaddr*)&si_other, slen) == -1)
{
    printf("Issue with send\n");
}

Any help would be appreciated.

Justin
  • 742
  • 5
  • 17
  • 34
  • 1
    If the string you get out of the buffer is empty, that implies the string you sent was empty. How are you constructing and sending the data? You also aren't checking the return value of `recvfrom`, so you have no idea if you've received all the data or just some of it. – Chris Dodd May 16 '14 at 02:42
  • You should post your sending code too. "extract a `uint32_t` and an `char*`" - your code (sensibly) extracts a ASCIIZ string, not a `char*` - make sure you didn't sent an actual `char*`. – Tony Delroy May 16 '14 at 02:48
  • You can debug this by setting a breakpoint at the `printf` and then viewing the buffer contents, or with a simple loop the prints the buffer contents `for (i=0;i<10;i++) printf( "%02x ", buf[i] );` (assuming that `buf` is a `char *`). – user3386109 May 16 '14 at 02:58
  • 2
    Note that `strlen(sendString)` is only 5, which means that you aren't sending the null terminator as part of the message. Hence, `strcpy` cannot be safely used on the receive side. – user3386109 May 16 '14 at 03:01
  • What is `buffer_size` set to in the call to `recvfrom` ? Is it big enough? – harmic May 16 '14 at 03:18
  • @harmic: buffer_size was set to 512 bytes. – Justin May 16 '14 at 03:33

1 Answers1

0

You need to make the send buffer one byte bigger to account for the 0 termination of the char string.

char* buffer = (char*)malloc(strlen(sendString) + 1 + sizeof(int));
Jiminion
  • 5,080
  • 1
  • 31
  • 54