Sending structure using recvfrom () and sendto ()

I use the C language , which is a common platform for server and client.

I have a structure of a certain type that I want to send to the client from the server.

For example,

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 the structure from the server to the client. But from the above code snippets, I get segmentation errors, and I'm not sure if such a structure transfer is possible. Is there a way out?

+3
source share
6 answers

-, malloc(), -. sendto()/recvfrom(), struct hostent , , , , .

+6

hp

+4

, , , , . , . , , , raw (. Petros)

, hp , , , . sizeof (hp) , -. , sendto, . :

struct hostent *hp;

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

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

. recvfrom . . :

// Store on the stack
struct hostent h;

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

// 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);
+4

hp , ?

+1

, :

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);

.

+1
source

By the way, if I consider a very general question in your post, that is, β€œI want to send the structure from the server to the client”, I would recommend looking at the following publication in SO:

Transferring a structure through Sockets in C

0
source

Source: https://habr.com/ru/post/1714331/


All Articles