1

ネットワーク転送用に C で構造体を定義したいと考えています。たとえば、可変長の動物名を含む Animal 構造体を転送したいと考えています。

私の知る限り、1つの方法はusing a predefined length of char array、またはusing a buffer構造体であり、バッファを解析できます(たとえば、最初の4バイトは動物の名前の長さで、その後に動物の名前、および他のフィールドの長さと他のフィールドの値が続きます)、利点後者の方法の特徴は、次のコードが示すように、変数名の長さを許可することです。

struct Animal
{
    char   name[128];
    int    age;
}

また:

struct Animal
{
    int    bufferLen;
    char*  pBuffer;
}

私の質問は: 私のアプローチは正しいですか? つまり、構造体を転送する標準的な方法があり、より良い方法はありますか?

私の2番目の質問は、パディングに注意を払う必要がありますか、つまり使用する必要があります#pragma pack(push/pop, n)か?

前もって感謝します!

4

1 に答える 1

3

どちらも問題なく動作しますが、パックされた固定長を使用すると処理が 少し簡単sturctになりますが、必要以上のデータを送信する可能性があります。132

//packed struct
struct Animal {
    char   name[128];
    int    age;
};

Animal a = {"name", 2};
send(fd, &a, sizeof(a), 0);
//and you're done

一方、可変長フィールドでは、メモリを割り当てて 1 つのパケットにパックするためにより多くの作業が必要になりますが、必要な正確な9バイト数 (この場合はバイト) を送信できます。

//not necessarily packed   
struct Animal {
    char   *name;
    int    age;
};

//some arbitrary length
int name_length = 50;
//you should check the result of malloc
Animal a = {malloc(name_length), 2}; 

//copy the name
strcpy(a.name, "name");

//need to pack the fields in one buff    
char *buf = malloc(strlen(a.name)+ 1 + sizeof(a.age));
memcpy(buf, a.name, strlen(a.name)+1);
memcpy(buf, &a.age, sizeof(a.age));

send(fd, buf, strlen(a.name)+ 1 + sizeof(a.age));
//now you have to do some cleanup
free(buf);
free(a.name);

編集:これはもちろん、自分で実装したい場合は、ライブラリを使用してデータをシリアル化できます。また、Beej's Guide to Network Programming のシリアライゼーション コードの例を確認してください。

于 2012-11-07T05:52:10.493 に答える