我试图在C中使用TCP套接字编程实现客户机 - 服务器程序通信。 它位于安装了Linux操作系统的两台64位机器之间。 我想在两个进程之间传递一个c-struct。两个64位机器之间的TCP套接字编程
为此,我尝试使用一个pack - unpack()functioanlity。
请考虑下面的代码snipt
/*---------------------------------------------------------
on the sending side I have:
---------------------------------------------------------*/
struct packet {
int64_t x;
int64_t y;
int64_t q[maxSize];
} __attribute__((packed));
int main(void)
{
// build packet
struct packet pkt;
pkt.x = htonl(324);
pkt.y = htonl(654);
int i;
for(i = 0; i< maxSize; i++){
pkt.q[i] = i; **// I also try pkt.q[i] = htonl(i);**
}
// and then do the send
}
/*-----------------------------------------------------------------------------
in the receiving side:
-----------------------------------------------------------------------------*/
struct packet {
int64_t x;
int64_t y;
int64_t q[maxSize];
} __attribute__((packed));
static void decodePacket (uint8_t *recv_data, size_t recv_len)
{
// checking size
if (recv_len < sizeof(struct packet)) {
fprintf(stderr, "received too little!");
return;
}
struct packet *recv_packet = (struct packet *)recv_data;
int64_t x = ntohl(recv_packet->x);
int64_t y = ntohl(recv_packet->y);
int i;
printf("Decoded: x=%"PRIu8" y=%"PRIu32"\n", x, y);
for(i=0;i<maxSize;i++){
**//int64_t res = ntohl(recv_packet->q[i]); I also try to print res**
printf("%"PRIu32"\n" , recv_packet->q[i]);
}
}
int main(int argc, char *argv[]){
// receive the data and try to call decodePacket()
int8_t *recv_data = (int8_t *)&buf; //buf is the data received
size_t recv_len = sizeof(buf);
**decode_packet(recv_data, recv_len);**
}
//-----------------------------------------------------------------------------
现在的问题是,我正确地接收到在结构中的x和y的值, 但在结构中的阵问:我收到了一个奇怪的编号,可能的内存碎片值,(我尝试使用memset()在从另一端接收数据之前用零填充数组,在这种情况下接收全零值)
我不明白为什么我没有收到结构中数组的正确值。
请注意,我尝试与出htonl(),而投入结构, 而在另一侧前填充阵列:以与出再用ntohl(),而阵列从结构解码
任何帮助将理解的,
您的接收端有几种不匹配的打印格式 - 这会导致未定义的行为。修复这些并再试一次? – 2012-08-07 17:14:14
由于问题很可能出现在发送或接收代码中,因此您忽略了重要的位。一种可能性是该结构需要在两端声明为打包(取决于你如何尝试发送/接收它)。 – 2012-08-07 17:15:09
是的。而这在编译器插入不同填充的两个Linux之间甚至不起作用。你最好连续化数值。甚至不要尝试直接转移结构。 – 2012-08-07 17:17:47