问题描述
我有定义,以便在不同的操作系统(TCP网络)发送几种结构。
定义的结构是:
I have several structures defined to send over different Operating Systems (tcp networks).Defined structures are:
struct Struct1 { uint32_t num; char str[10]; char str2[10];}
struct Struct2 { uint16_t num; char str[10];}
typedef Struct1 a;
typedef Struct2 b;
的数据存储在文本文件中。
数据格式是这样:
The data is stored in a text file. Data Format is as such:
- 123
- 派
- 壳
Struct1一个存储为3个独立的参数。然而,struct2是具有两个第二和第三行两个独立的参数的存储为char海峡[]。问题是,当写到在多个网络服务器,该数据没有被正确接收。有迹象表明,不同的参数在结构中分离大量的空间。如何确保正确的发送和填充时,我写信给服务器?我如何正确地存储数据(动态缓冲区或固定缓冲)?
Struct1 a is stored as 3 separate parameters. However, struct2 is two separate parameters with both 2nd and 3rd line stored to the char str[] . The problem is when I write to a server over the multiple networks, the data is not received correctly. There are numerous spaces that separate the different parameters in the structures. How do I ensure proper sending and padding when I write to server? How do I store the data correctly (dynamic buffer or fixed buffer)?
写的例子:写(FD,和放大器;一,的sizeof(typedef结构一));这是正确的?
Example of write: write(fd,&a, sizeof(typedef struct a)); Is this correct?
问题接收端输出为struct2:
Problem Receive Side Output for struct2:
- 123(,)
- 0(图,饼图)
- 0(地壳)
正确的输出
123(馅饼,地壳)
123(Pie, Crust)
推荐答案
写(FD,和放大器;一,的sizeof(A));
是不正确的;至少不可移植性,因为C编译器可能会引入元素之间填充,以确保正确对齐。 的sizeof(typedef结构一)
甚至没有意义了。
write(fd,&a, sizeof(a));
is not correct; at least not portably, since the C compiler may introduce padding between the elements to ensure correct alignment. sizeof(typedef struct a)
doesn't even make sense.
你应该如何发送的数据取决于您的协议的规格。特别是,该协议规定了广泛不同的字符串发送方式。它通常是最安全的结构
成员分别发送;或者通过多次调用写或 writev则(2)
。例如,要发送
How you should send the data depends on the specs of your protocol. In particular, protocols define widely varying ways of sending strings. It is generally safest to send the struct
members separately; either by multiple calls to write or writev(2)
. For instance, to send
struct { uint32_t a; uint16_t b; } foo;
在网络上,其中 foo.a
和 foo.b
已经有一个正确的顺序,你会怎么做是这样的:
over the network, where foo.a
and foo.b
already have the correct endianness, you would do something like:
struct iovec v[2];
v[0].iov_base = &foo.a;
v[0].iov_len = sizeof(uint32_t);
v[1].iov_base = &foo.b;
v[1].iov_len = sizeof(uint16_t);
writev(fp, v, 2);
这篇关于发送结构比在C正确的填充和字节顺序插座的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!