# memcpy / sendto issue

This topic is 4758 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I'm attemping to send some header information across the network using UDP sockets. The client generates the following message and sends it the server.
char *msg;
u_short length = htons(514);
u_char id = 50;
u_short offset = htons(500);
u_char flag = 49;

msg = (char *)malloc(sizeof(char)*14);
memset(msg, 0, 14);  //zero out the memory

sendto(sock, msg, strlen(msg), 0, (struct sockaddr *)&dest, (socklen_t)sizeof(dest));


The server receives the message and parses the string.
u_short size;
u_long source;
u_long dest;
u_char id;
u_short offset;
u_char flag;

recvfrom(sock, msg, sizeof(msg), 0, (struct sockaddr *)&from, (socklen_t *)&fsize);

memcpy(&size, msg, 2);
memcpy(&source, msg+2, 4);
memcpy(&dest, msg+6, 4);
memcpy(&id, msg+10, 1);
memcpy(&offset, msg+11, 2);
memcpy(&flag, msg+13, 1);


This works as expected unless I set one of the u_shorts(id, length) to a value less than 256. Is there anyway I can make this work with values between 0 and 255?

##### Share on other sites
Quote:
 strlen(msg)

You formed "msg" using memcpy(), not strcpy(). It's a binary blob of data, not a C string. Thus, you should send "msg" using the length of the msg buffer, not using the strlen() of it. Just put a breakpoint at the send line, and examine the memory at "msg" and you'll understand why this is.

##### Share on other sites
Thanks for taking the time to point out my mistake hplus0603. Everything works fine now.