Sign in to follow this  
Eagor

memcpy / sendto issue

Recommended Posts

Eagor    122
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?

Share this post


Link to post
Share on other sites
hplus0603    11356
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 this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this