Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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;
    . . .
} 

This is the struct that I have defined:

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];
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
179 views
Welcome To Ask or Share your Answers For Others

1 Answer

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)

Then,

memcpy(dnsAnswer, buf, sizeof(DNS_Answer));

If their data formats aren't same, you have to parse them by yourself, or you can use DFDL (A data format descripation language.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...