Question

I have the following struct:

struct Packet
{
    int seqNum;
    int ackNum; 
    int numBytes;
    char* payload;
};

Which I would like to send over UDP. I'm currently doing this as:

struct Packet p = {1,0,8,"testing"};
int payloadSize = p.numBytes;
char* payload = (char*)malloc(payloadSize);
memcpy(payload, &p, payloadSize);
int bytesSent = sendto(mySocket, payload, payloadSize, 0,
                        (const struct sockaddr *)&toNode,length);

The number of bytes sent is correct - but the data is garbled. Am I doing this wrong? On the receiver size I do something like:

    int n;
    char buffer[MTU];
    bzero(buffer,MTU );
    unsigned int length = sizeof(struct sockaddr_in);
    struct sockaddr_in from;

    n = recvfrom(mySocket,buffer,1472,0,(struct sockaddr *)&from, &length);

    if (n < 0) 
        perror("recvfrom");
    else
    {
        cout << "Recieved " << n << " bytes of data\n-|-\n";
        char* seqNum = (char*)malloc(sizeof(int));
        memcpy(seqNum, &buffer, 4);
        cout << "SeqNum: " << seqNum << endl;
    }

Output

Received 8 bytes of data
SeqNum: [garbage]
Was it helpful?

Solution

You have this char* in your struct...

You'll have to create (dynamically) a buffer capable of containing the 3 ints and the characters of the string, compose it (strcpy) and send the buffer.

Answering a OP question in the comments below

A few things to consider for a stable solution: For integers of 2 or more bytes: you should always use network order, not the endian-ness of "your" system. For char[], there are several things to consider: encoding, prefixed by length (1, 2, 4 byte integer) or a trailing 0 byte. -- See also ASN.1 or google TLV (type, length, value). -- You could avoid all of this by going XML or JSON.

OTHER TIPS

  1. It's a bad idea to send binary structures "raw" over the network. You can't trust that the receiver's compiler has laid out the structure in the exact same way.
  2. How did you expect the char * field to make sense? It's going to send the value of the pointer, but none of the characters. Clearly this is useless to the reciever, who can't follow the pointer back over the network into your process' memory.

You need to do proper serialization of data, you can't just dump raw structures out.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top