Sending structure using recvfrom() and sendto()

烂漫一生 提交于 2019-12-03 17:27:47

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.

I'd remove the & in front of hp

In general you want to avoid transferring raw structures over networks unless they have specifically been designed for use as network transport, or unless you are absolutely sure that both ends will always be exactly the same architecture. Differences in padding and byte ordering may cause the data to appear garbled at the other end. The particular type of struct you are trying to transfer just will not work being sent raw (See the answer by Petros)

The problem in your send code is that hp is a pointer and you are treating it like it is the data it points to. sizeof(hp) returns the size of a pointer, not the size of the pointed-to hostent struct. Also, you are creating a pointer-to-pointer in the second argument of sendto when you do not mean to. The sending code should read:

struct hostent *hp;

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

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

You also have a problem in the receive code. You are supposed to allocate space for recvfrom to store the data it received. It does not allocate it for you. Change your receive code to one of these two:

// Store on the stack
struct hostent h;

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

or

// Store on the heap, be sure to free() when done
struct hostent * hp = malloc(sizeof(struct hostent));

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

If hp is a pointer, why are you taking its address?

You should correct the code as shown below:

struct hostent *p_hp = gethostbyname("www.google.com");
struct sockaddr_in cli_addr;
sendto(sockDes,p_hp,sizeof(hostent),0,(SOCKADDR *)&cli_addr,sizeof(cli_addr));


struct hostent hp;
struct sockaddr_in serv_addr;
int size_serv_addr = sizeof(serv_addr);
msg=recvfrom(mysock,&hp,sizeof(hostent),0,(SOCKADDR *)&serv_addr,&size_serv_addr);

It would always help to read the documentation on socket functions.

AamodG

By the way, if I consider the very generic question in your post, i.e. "I want to send a structure from the server to the client", I would recommend looking at the following post on SO:

Passing a structure through Sockets in C

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!