简体   繁体   中英

Sending a structure over socket in c

I am writing a program which uses socket programming in c.

In this program a client and server keep transmitting and receiving data.

When I send and receive integers over the socket using this kind of code

//in the program sending data
int data;
len= send(s,(char *)&(data),sizeof(data),0);

//in the program receiving data
int num;
len = recv(s,&num, sizeof(num) , 0);

The above code is working fine and I am able to transmit and receive numbers.

In one case I am trying to send a structure of the form

struct sample{
int num;
char chain[10*hops+10];
};

//in the program sending data
struct sample s1;
len= send(s,(char *)&(s1),sizeof(s1),0);

//in the program receiving data
struct sample s2;
len = recv(s,&s2, sizeof(s2) , 0);

In the example where I am trying to send and receive structure it is not working. How to send and receive the struct successfully ?

Note: 1) Hops is a pre defined variable.The value of hops is same in both the programs. 2) By not working I meant : when I receive the struct and print the value in the the num. It is printing not the same value but zero!

if you are trying to send the struct you must use serialization and deserialization, read about that, you can start with :

Serialization issues while sending struct over socket

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM