user2501289
user2501289

Reputation: 49

read/write struct to a socket

I am trying to write from client a struct to the server with socket.

the struct is :

typedef struct R
{
int a;
int b;
double c;
double d;
double result[4]; 
}R;

The struct is the same at the 2 programs(server,client) and i malloc for the struct in both.

the client program:

struct R* r;

malloc..

...(fill the struct with data)

write(socket_fd,(void*)r,size of(R));


the Server program:

struct R* r;

malloc..

read(client_fd,(R*)r,size of(R));


This is not passing the struct from client to server..

How to write the struct to the server by socket??

Upvotes: 2

Views: 2183

Answers (2)

user3321437
user3321437

Reputation: 95

I'm assuming you are getting some data, but not in the form you are expecting. If so, it might also help to add a breakpoint in gdb and inspect the memory of r, in the client code. You could fill the struct in sender code with 0xdeadbeef or similar debug strings(http://en.wikipedia.org/wiki/Magic_number_%28programming%29#Magic_debug_values), to identify your data in the client memory more easily. I have found that very helpful for debugging. Like some of the other answers mentioned, endianess and partial data might be the problem. Checking the return values and error codes will help too.

Upvotes: 0

fkl
fkl

Reputation: 5535

Some basic elements of network programming are:

  1. One read or write call might not write the total bytes you intend to read/write. Check the return value of call. It would return number of bytes read/written. If less bytes have been written, you should call write in a loop until all data has been written. Same applies to read.

  2. Endianess of machine also matters. If you wrote an int which was little endian (e.g. x86), when travelling on the network it would be converted into a big endian value. You need to use apis such as htons, ntohs in POSIX to accommodate that.

These are just starting points, but the most likely reasons of data not reaching destination in the form as you expected.

Upvotes: 3

Related Questions