CでTCPソケットプログラミングを使用してクライアントサーバープログラム通信を実装しようとしています。これは、LinuxOSがインストールされている2台の64ビットマシン間です。2つのプロセス間でc-structを転送したいと思います。
このために、私はパックを使用してみました-unpack()機能。
次のコードスニプトを検討してください
/*---------------------------------------------------------
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の値を正しく受け取っていることですが、構造体の配列qで、メモリグラブ値の可能性がある奇妙な数値を受け取っています(memset()を使用して反対側からデータを受信する前にゼロで配列します。この場合、すべてのゼロの値が受信されます)
構造体の配列の正しい値を受け取っていない理由がわかりません。
構造体を配置する前に配列を埋めるときにhtonl()を使用して、または使用せずに、反対側で:構造体から配列をデコードするときにntohl()を使用して使用することに注意してください。
どんな助けでもありがたいです、