Home > Enterprise >  How to send structs with pointers through sockets in C
How to send structs with pointers through sockets in C

Time:11-25

I have this struct in my server and client

typedef struct email{

unsigned char * message;

}mail;

And I want to send it through TCP sockets in C. But I have problems when the struct contains a pointer. I want to send all together, not parameter by parameter

I have this code for server and client:

Client:

    mail messageServer;
    printf("Choose message: ");
    scanf("%s",messageServer.message);
    printf("Message: %s\n", messageServer.message);
    send(fd, &messageServer, sizeof(struct email), 0);

Server:

mail messageServer;

    printf("Before recv\n");

    recv(fd2, &messageServer, sizeof(struct email), 0);

    printf("After recv");

    printf("Message: %s\n",messageServer.message);

But when I execute it, I have a segmentation fault on server

CodePudding user response:

You can't send pointers over any form of data protocol, doing so doesn't make any sense. Only send data.

In this case only the contents pointed at by message are useful information. The surrounding struct and the pointer message are only of concern to your local application.

It's common practice to write serialization/deserialization routines that convert between structs and raw data. You usually need those anyway, to deal with other things such as network endianess and struct alignment.

CodePudding user response:

In general you cannot send the structure with all referenced data in one send call.

The pointer can point anywhere, so without specific preconditions, the memory where the pointer might point to is not necessarily next to the memory where the structure is stored.

The pointer value from the client is not a valid pointer when transferred to the server, so even if you would transfer all data you would have to adjust the pointer on the server.

Read about Serialization

There is an error in the client code:

    mail messageServer;
    printf("Choose message: ");
    scanf("%s",messageServer.message);

The pointer field messageServer.message is uninitialized. You have to assign the address of a buffer where scanf can write the data.

Additionally you should limit the string length in the scanf format string to avoid writing past the end of the array.

  • Related