I would like to send a struct from my client program to a server program (I am writing both the server and the client programs). Also, in case it is important I am writing on a 32-bit OS Linux and both the client and the server will be running on the same systems. Here is my struct:
struct msg_to_server {
int type_of_msg;
int type;
int flag;
int pid;
char name[MAX_WORD];
char client_name[MAX_WORD];
int child_timeout;
int numberKilled;
};
I know that if I am sending an int I need to use htonl(int) to convert the unsigned int from host byte order to network byte order, but what do I do in case of a struct?
Any help would be most appreciated.
If you know you are sending and receiving from the same kind of systems, then there’s no need to convert integers to network byte order. That’s only important if you’re sending between systems with different endianness.
You can, at a minimum, simply send the bytes of the whole structure over the socket, with no translation step at all.
However, be aware that if you’re using TCP, then the protocol may not return all the bytes you request on
recv(). You might have to callrecv()more than once to retrieve all the bytes sent by the client. If you are using UDP, you don’t have to worry about this, but you will have other considerations like unreliable delivery.