R – How to copy a char[] in c into the struct

cmemcpysocketsstructudp

I am trying to send my struct over a UDP socket.

struct Packet {
int seqnum;
char data[BUFFERSIZE];
};

So on the sender I have

bytes = sizeof(packet);
char sending[bytes];
bzero(sending, bytes);
memcpy((void *) sending, (void *) &packet, sizeof(bytes));
bytes = sendto(sockfd, sending, sizeof(sending), 0,
    (struct sockaddr *) &client, clientSize);

So I'm hoping that copies my struct into the Char[].

On the receiver I have

int bytes;
bytes = sizeof(struct Packet);
char recv[bytes];
bytes = recvfrom(sockfd, recv, bytes, 0,
    (struct sockaddr *) &client, &clientSize);
memcpy((void *) currentpkt, (void *) recv, bytes);

However on the receiver with memcpy((void *) currentpkt, (void *) recv, bytes); I get an error:

error: cannot convert to a pointer type

What am I doing wrong? Is there a better way to send my struct over a UDP socket?

***** UPDATE *****

Thanks for the answers everyone. In the end I missed the '&' but my code now looks like this.

Sender:

void udt_send(struct Packet packet) {
    int bytes;
    bytes = sendto(sockfd, (char *) &packet, sizeof(packet), 0,
            (struct sockaddr *) &client, clientSize);
}

Receiver:

bytes = recvfrom(sockfd, (char *) &currentpkt, bytes, 0,
        (struct sockaddr *) &client, &clientSize);

In C its nice that we can just cast it to a char and send the bytes over.

Best Answer

currentpkt is of struct type; you need to get a pointer to the struct to get this to work:

memcpy(&currentpkt, recv, bytes);

For your second question, you have some other problems. What if you receive more bytes in a packet than sizeof(struct Packet)? As it's written now, you'll overrun your struct.

What if the client and server applications are compiled using different compilers or settings, or on platforms with different endianness? In this case, the struct might be different sizes on the two platforms and may be laid out in memory differently.

Related Topic