Sending structure using recvfrom() and sendto()

Biswajyoti Das picture Biswajyoti Das · Aug 4, 2009 · Viewed 16.1k times · Source

I am using C language which is a common platform for both the server and the client.

I have a structure of a particular type which I want to send to the client from the server.

For e.g.

SERVER CODE

 //necessary declarations

struct hostent *hp;

hp=gethostbyname("www.google.com");

sendto(sockDes,&hp,sizeof(hp),0,(struct sockaddr *)&cli_addr,sizeof(cli_addr));

CLIENT CODE

struct hostent *hp;

msg=recvfrom(mysock,&hp,sizeof(hp),0,(struct sockaddr)&serv_addr,&size_len);

So , basically I want to send a structure from the server to the client. But from the above pieces of code I am getting segmentation faults , and I am not sure whether such structure transfer is feasible. Is there any way out?

Answer

PetrosB picture PetrosB · Aug 4, 2009

First, you have to malloc() in order to allocate memory for the struct hostent. You can transfer a struct through sendto()/recvfrom() but since struct hostent contains pointers, the members of this struct that are pointers have no meaning as soon as they are transfered to the other end.