I'm having difficulty retrieving data from a buffer using memcpy.
First, I memcpy some variables to the buffer:
int l1_connect(const char* hostname, int port) {
char *msg = "Hi, I'm a message";
uint16_t sender_id = htons(1);
uint16_t packet_size = htons(sizeof(packet_size)+sizeof(sender_id)+strlen(msg));
printf("l1_connect():\nsender_id: %d, packet_size: %d\n\n", ntohs(sender_id), ntohs(packet_size));
char buf[100];
memcpy(&buf, &sender_id, sizeof(sender_id));
memcpy(&buf+sizeof(sender_id), &packet_size, sizeof(packet_size));
memcpy(&buf+sizeof(sender_id)+sizeof(packet_size), &msg, strlen(msg));
int bytes_sent = l1_send(1, buf, sizeof(buf));
}
Then I try to extract this data (check before sending via UDP socket):
int l1_send( int device, const char* buf, int length ) {
uint16_t id = 0;
uint16_t size = 0;
char msg[50];
memcpy(&id, &buf, sizeof(id));
memcpy(&size, &buf+sizeof(id), sizeof(size));
int remaining = ntohs(size) - (sizeof(id) + sizeof(size));
printf("l1_send():\nremaining: %d\n", remaining);
memcpy(&msg, &buf+sizeof(id)+sizeof(size), 50);
msg[49] = '\0';
printf("id: %d\n", ntohs(id));
printf("size: %d\n", ntohs(size));
printf("msg: %s\n", msg);
return 0;
}
As you can see, the values are not quite what I expect. Can someone tell me what I am doing wrong?
source
share