【发布时间】:2016-01-11 21:48:44
【问题描述】:
看了很多与我的问题相关的答案,但在我的条件下确实用不上。
我正在 Linux 域下使用 C 语言的套接字编程构建一个网络模块。 我必须实现一个函数,它可以发送一个由 int、char、char * 和一些其他结构(嵌套结构)组成的结构。
struct EnQuery
{
char type[6]; // insert, select , update , delete
char * columns; //note here, it's an array of big, {name, age, sex, position, email} not in string
struct Values * values; //an array of values(another struct), {tom, 23, male, student, tom@compan.com} is represented by the second struct values, not in string
struct condition * enCondition; // array of condition, "name=tom and age>30" is represnted by the third struct condition
short len;
short rn;
};
struct Values
{
char * doc;
char key[2];
char s;
};
struct condition
{
short k;
struct condition * children;
};
上面是我要发送的结构。 我正在声明变量并使用 send() 函数通过套接字发送。
我必须如何通过套接字发送 char *? 或者有没有办法方便地调整 char 数组的长度?
P.S 我不能使用外部库
【问题讨论】:
-
只需确定您要使用的有线格式并编写代码来转换为该有线格式。查看现有规范(BER、XML、JSON 等)以获取想法。
-
我不能使用任何外部库..
-
你的 strcts 有指针,不能传输,因为它们在接收端无效——你需要序列化和反序列化数据——你怎么做会有一百万个很好的答案。
-
所有带有星号 (
*) 的东西都需要序列化,而不仅仅是chars。如果您没有任何指针,您可以按原样发送结构(假设接收器具有相同的字节序和内存填充等)。 -
不要使用结构体作为网络协议。使用网络协议作为网络协议。首先在八位字节中定义协议,然后自己编写一个 API 来发送和接收它。
标签: c sockets pointers struct network-programming