用C打印结构

时间:2016-10-08 00:55:30

标签: c file io printf fwrite

我在wireshark源代码中进行了一些更改。在某个特定点上,我打印出一个名为SSLDecoder的结构,如此

FILE *f;  
f=fopen("file.txt","a+");
size_decoder=sizeof(SslDecoder);  
for(i=0; i < size_decoder; i++){
    fprintf(f,"%02x",*(ssl_session->client_new+i));
}
fprintf(f,"\n");

ssl_session的类型为struct SslDecryptSession,定义为

typedef struct _SslDecryptSession {
    guchar _master_secret[SSL_MASTER_SECRET_LENGTH];
    guchar _session_id[256];
    guchar _client_random[32];
    guchar _server_random[32];
    StringInfo session_id;
    StringInfo session_ticket;
    StringInfo server_random;
    StringInfo client_random;
    StringInfo master_secret;
    StringInfo handshake_data;
    /* the data store for this StringInfo must be allocated explicitly with a capture lifetime scope */
    StringInfo pre_master_secret;
    guchar _server_data_for_iv[24];
    StringInfo server_data_for_iv;
    guchar _client_data_for_iv[24];
    StringInfo client_data_for_iv;

    gint state;
    SslCipherSuite cipher_suite;
    SslDecoder *server;
    SslDecoder *client;
    SslDecoder *server_new;
    SslDecoder *client_new;
    gcry_sexp_t private_key;
    StringInfo psk;
    guint16 version_netorder;
    StringInfo app_data_segment;
    SslSession session;
} SslDecryptSession;

SslDecoder的类型为

typedef struct _SslDecoder {
    SslCipherSuite* cipher_suite;
    gint compression;
    guchar _mac_key_or_write_iv[48];
    StringInfo mac_key; /* for block and stream ciphers */
    StringInfo write_iv; /* for AEAD ciphers (at least GCM, CCM) */
    SSL_CIPHER_CTX evp;
    SslDecompress *decomp;
    guint32 seq;
    guint16 epoch;
    SslFlow *flow;
} SslDecoder;

但是,打印到文件的输出是不规则的。 示例输出位于pastebin

有人可以告诉我我做错了吗?

我后来在文件中使用此输出来填充这样的另一个解码器(现在,因为文件的不规则打印,我面临一个seg错误)

SslDecoder *temp_decoder;
c = malloc(sizeof(SslDecoder));

for (i=0; i<sizeof(SslDecoder); i++){
    fscanf(f,"%02x",&c[i]);
}
memcpy(temp_decoder,c, sizeof(SslDecoder));

1 个答案:

答案 0 :(得分:1)

执行指针运算时,指针偏移指向的类型大小的倍数;它 not 将指针偏移指定数量的字节。请注意,如果您有T* p,则*(p + i)相当于p[i]

在您的代码中,您可以:

size_decoder=sizeof(SslDecoder);  
for(i=0; i < size_decoder; i++){
    fprintf(f,"%02x",*(ssl_session->client_new+i));
}

*(ssl_session->client_new+i)在每次迭代时将client_new指针偏移i * sizeof (SslDecoder)个字节。

相反,您打算在每次迭代时仅将指针前进一个字节,因此您必须对指向char的指针执行指针算术:

size_decoder=sizeof(SslDecoder);  
const unsigned char* p = (unsigned char*) ssl_session->client_new;
for(i=0; i < size_decoder; i++){
    fprintf(f,"%02x", p[i]);
}

在阅读文件时,您同样需要做类似的事情。我还应该在你的阅读代码中指出:

SslDecoder *temp_decoder;
c = malloc(sizeof(SslDecoder));

for (i=0; i<sizeof(SslDecoder); i++){
    fscanf(f,"%02x",&c[i]);
}
memcpy(temp_decoder,c, sizeof(SslDecoder));

memcpy来电不正确;你没有为temp_decoder分配任何内存。您根本不需要使用memcpy

SslDecoder *temp_decoder = malloc(sizeof *temp_decoder);
unsigned char* p = (unsigned char*) temp_decoder;
for (i=0; i<sizeof(SslDecoder); i++){
    int temp; // "%x" corresponds to an int type
    fscanf(f, "%02x", &temp);
    p[i] = (unsigned char) temp;
}