C ++:使用缓冲区中的数据填充结构 [英] C++: Populate a struct with data from a buffer
问题描述
我想知道是否可以就如何从缓冲区中获取数据并将其加载到结构中提出一些建议。例如,我正在处理DNS响应缓冲区。我需要填充DNS答案结构,以便我可以解释数据。到目前为止,我有以下内容:
I was wondering if I could have some recommendations on how to take data from a buffer and load them into a struct. For example, I have dealing with a DNS response buffer. I need to populate a DNS answer struct so that I can interpret the data. So far, I have the following:
int DugHelp::getPacket() {
memset(buf, 0, 2000); // clearing the buffer to make sure no "garbage" is there
if (( n = read(sock, buf, 2000)) < 0 {
exit(-1);
}
// trying to populate the DNS_Answers struct
dnsAnswer = (struct DNS_Answer *) & buf;
. . .
}
这是我定义的结构:
struct DNS_Answer{
unsigned char name [255];
struct {
unsigned short type;
unsigned short _class;
unsigned int ttl;
unsigned in len;
} types;
unsigned char data [2000];
};
推荐答案
这取决于buf的数据格式。如果该格式与DNS_Answer相同,则可以使用 memcpy 。如果它们的格式相同,则应 a首先优先考虑字节。
It depends on the data format of buf. If the format is same with DNS_Answer. You can use memcpy. If their formats are same, you should align the bytes first.
#pragma pack (1)
struct DNS_Answer{
unsigned char name [255];
struct {
unsigned short type;
unsigned short _class;
unsigned int ttl;
unsigned in len;
} types;
unsigned char data [2000];
};
#pragma pop(1)
然后,
memcpy(dnsAnswer, buf, sizeof(DNS_Answer));
如果它们的数据格式不同,则必须自己解析它们,或者可以使用 DFDL (一种数据格式描述语言。)
If their data formats aren't same, you have to parse them by yourself, or you can use DFDL (A data format descripation language.)
这篇关于C ++:使用缓冲区中的数据填充结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!