memcpy / sendto issue

Started by
1 comment, last by Eagor 19 years, 2 months ago
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_long source = htonl(ip_address);
u_long dest = htonl(ip_address);
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
memcpy(msg, &length, 2);  //add length
memcpy(msg+2, &source, 4);  //add source
memcpy(msg+6, &destination, 4);  //add destination
memcpy(msg+10, &id, 1);  //add id
memcpy(msg+11, &offset, 2);  //add offset
memcpy(msg+13, &flag, 1); //add flag

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?
Advertisement
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.
enum Bool { True, False, FileNotFound };
Thanks for taking the time to point out my mistake hplus0603. Everything works fine now.

This topic is closed to new replies.

Advertisement