简体   繁体   English

通过C中的套接字传递结构

[英]Passing a structure through Sockets in C

I am trying to pass whole structure from client to server or vice-versa. 我试图将整个结构从客户端传递到服务器,反之亦然。 Let us assume my structure as follows 让我们假设我的结构如下

struct temp {
  int a;
  char b;
}

I am using sendto and sending the address of the structure variable and receiving it on the other side using the recvfrom function. 我使用sendto并发送结构变量的地址,并使用recvfrom函数在另一侧接收它。 But I am not able to get the original data sent on the receiving end. 但我无法获得接收端发送的原始数据。 In sendto function I am saving the received data into variable of type struct temp. 在sendto函数中,我将接收到的数据保存到struct temp类型的变量中。

n = sendto(sock, &pkt, sizeof(struct temp), 0, &server, length);
n = recvfrom(sock, &pkt, sizeof(struct temp), 0, (struct sockaddr *)&from,&fromlen);

Where pkt is the variable of type struct temp. 其中pkt是struct temp类型的变量。

Eventhough I am receiving 8bytes of data but if I try to print it is simply showing garbage values. 虽然我收到8字节的数据,但如果我尝试打印它只是显示垃圾值。 Any help for a fix on it ? 任何帮助修复它?

NOTE: No third party Libraries have to be used. 注意: 不得使用第三方库。

EDIT1: I am really new to this serialization concept .. But without doing serialization cant I send a structure via sockets ? 编辑1: 我对这个序列化概念真的很 陌生 。但是如果不进行序列化,我不能通过套接字发送结构?

EDIT2: When I try to send a string or an integer variable using the sendto and recvfrom functions I am receiving the data properly at receiver end. EDIT2: 当我尝试使用sendtorecvfrom函数发送字符串或整数变量时,我在接收端正确接收数据。 Why not in the case of a structure? 为什么不在结构的情况下? If I don't have to use serializing function then should I send each and every member of the structure individually? 如果我不必使用序列化功能,那么我应该单独发送每个结构的成员吗? This really is not a suitable solution since if there are 'n' number of members then there are 'n' number of lines of code added just to send or receive data. 这实际上不是一个合适的解决方案,因为如果有'n'个成员,那么只有添加'n'个代码行才能发送或接收数据。

This is a very bad idea. 这是一个非常糟糕的主意。 Binary data should always be sent in a way that: 二进制数据应始终以下列方式发送:

Don't ever write a whole struct in a binary way, not to a file, not to a socket. 不要以二进制方式编写整个结构,而不是文件,而不是套接字。

Always write each field separately, and read them the same way. 始终分别编写每个字段,并以相同的方式读取它们。

You need to have functions like 你需要有像这样的功能

unsigned char * serialize_int(unsigned char *buffer, int value)
{
  /* Write big-endian int value into buffer; assumes 32-bit int and 8-bit char. */
  buffer[0] = value >> 24;
  buffer[1] = value >> 16;
  buffer[2] = value >> 8;
  buffer[3] = value;
  return buffer + 4;
}

unsigned char * serialize_char(unsigned char *buffer, char value)
{
  buffer[0] = value;
  return buffer + 1;
}

unsigned char * serialize_temp(unsigned char *buffer, struct temp *value)
{
  buffer = serialize_int(buffer, value->a);
  buffer = serialize_char(buffer, value->b);
  return buffer;
}

unsigned char * deserialize_int(unsigned char *buffer, int *value);

Or the equivalent, there are of course several ways to set this up with regards to buffer management and so on. 或者等效,当然有几种方法可以设置缓冲区管理等等。 Then you need to do the higher-level functions that serialize/deserialize entire structs. 然后,您需要执行序列化/反序列化整个结构的更高级函数。

This assumes serializing is done to/from buffers, which means the serialization doesn't need to know if the final destination is a file or a socket. 这假设序列化是从缓冲区完成的,这意味着序列化不需要知道最终目标是文件还是套接字。 It also means you pay some memory overhead, but it's generally a good design for performance reasons (you don't want to do a write() of each value to the socket). 它还意味着您需要支付一些内存开销,但出于性能原因,它通常是一个很好的设计(您不希望对套接字执行每个值的write())。

Once you have the above, here's how you could serialize and transmit a structure instance: 完成上述操作后,您可以通过以下方式序列化和传输结构实例:

int send_temp(int socket, const struct sockaddr *dest, socklen_t dlen,
              const struct temp *temp)
{
  unsigned char buffer[32], *ptr;

  ptr = serialize_temp(buffer, temp);
  return sendto(socket, buffer, ptr - buffer, 0, dest, dlen) == ptr - buffer;
}

A few points to note about the above: 关于上述几点需要注意:

  • The struct to send is first serialized, field by field, into buffer . 要发送的结构首先按字段逐序序列化为buffer
  • The serialization routine returns a pointer to the next free byte in the buffer, which we use to compute how many bytes it serialized to 序列化例程返回一个指向缓冲区中下一个空闲字节的指针,我们用它来计算它序列化的字节数
  • Obviously my example serialization routines don't protect against buffer overflow. 显然,我的示例序列化例程不能防止缓冲区溢出。
  • Return value is 1 if the sendto() call succeeded, else it will be 0. 如果sendto()调用成功,则返回值为1,否则为0。

Using the 'pragma' pack option did solved my problem but I am not sure if it has any dependencies ?? 使用'pragma'包选项确实解决了我的问题,但我不确定它是否有任何依赖?

#pragma pack(1)   // this helps to pack the struct to 5-bytes
struct packet {
int i;
char j;
};
#pragma pack(0)   // turn packing off

Then the following lines of code worked out fine without any problem 然后下面的代码行没有任何问题

n = sendto(sock,&pkt,sizeof(struct packet),0,&server,length);

n = recvfrom(sock, &pkt, sizeof(struct packet), 0, (struct sockaddr *)&from, &fromlen);

不需要为short整数类型和long整数类型编写自己的序列化例程 - 使用htons() / htonl() POSIX函数。

If you don't want to write the serialisation code yourself, find a proper serialisation framework, and use that. 如果您不想自己编写序列化代码,请找到正确的序列化框架,然后使用它。

Maybe Google's protocol buffers would be possible? 也许谷歌的协议缓冲可能吗?

Serialization is a good idea. 序列化是个好主意。 You can also use Wireshark to monitor the traffic and understand what is actually passed in the packets. 您还可以使用Wireshark监控流量并了解数据包中实际传递的内容。

Instead of serialising and depending on 3rd party libraries its easy to come up with a primitive protocol using tag, length and value. 而不是序列化和依赖于第三方库,它很容易使用标签,长度和值来提出原始协议。

Tag: 32 bit value identifying the field
Length: 32 bit value specifying the length in bytes of the field
Value: the field

Concatenate as required. 根据需要连接。 Use enums for the tags. 使用标签的枚举。 And use network byte order... 并使用网络字节顺序...

Easy to encode, easy to decode. 易于编码,易于解码。

Also if you use TCP remember it is a stream of data so if you send eg 3 packets you will not necessarily receive 3 packets. 此外,如果你使用TCP记住它是一个数据 ,所以如果你发送例如3个数据包,你不一定会收到3个数据包。 They maybe be "merged" into a stream depending on nodelay/nagel algorithm amongst other things and you may get them all in one recv... You need to delimit the data for example using RFC1006. 它们可能会根据nodelay / nagel算法“合并”到一个流中,您可以将它们全部放在一个recv中......您需要使用RFC1006来分隔数据。

UDP is easier, you'll receive a distinct packet for each packet sent, but its a lot less secure. UDP更容易,您将为每个发送的数据包收到一个不同的数据包,但其安全性要低得多。

如果要传输的数据格式非常简单,那么转换为ANSI字符串和从ANSI字符串转换是简单且可移植的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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