0
votes

So, I have to do library sending IPv4 packets (without libraries with prepared headers) and problem is that I can't access field in struct inside struct while using function, though eclipse does not see error, hint does not show that is possible.

Structs:

struct packet{
    struct ipv4hdr * iphdr;
    struct icmphdr * icmphdr;
    char * data;
};
struct ipv4hdr{
    u_int8_t version_length;
    u_int8_t type;
    u_int16_t total_length;
    u_int16_t id;
    u_int16_t frag_off;
    u_int8_t ttl;
    u_int8_t protocol;
    u_int16_t checksum;
    u_int32_t source;
    u_int32_t destination;
};

Pointers to function (that is requirement, both work):

struct packet *(*packetCreate)() = dlsym(lib, "createPacket");
void (*setIP)(struct packet *, u_int8_t, u_int8_t, u_int16_t, char*, u_int8_t, char*) = dlsym(lib, "prepareIP");

Creation of struct packet:

struct packet * createPacket(){
    struct packet * pack= malloc(sizeof(struct packet));
    return pack;
}

Now, calling fields inside main does show posssible fields:

struct packet * pack = packetCreate();
pack->iphdr->(CTRL+space displays all the fields)   //and eclipse automatically corrects all the . to ->

Meanwhile calling created pointer on function does not display fields while using hint and that causes segmentation fault (core dumped):

void prepareIP(struct packet * packet, u_int8_t length, u_int8_t type, u_int16_t id, char* destination, u_int8_t ttl, char *data){

    packet->iphdr->type = type;     //it is not treated by error, though any field causes crash
    //meanwhile hint
    packet->iphdr->(CTRL+space gets)ipv4hdr;

}

Question again is why I can't call specific field inside function that points to the original struct and how to do this inside that function

1
Show us how you allocate space iphdr points to.user694733
Didn't do that, switched the code like 1st answer, packetCreate() was (and still is) all the allocatingMyszsoda

1 Answers

0
votes

It looks like you forgot to allocate space for struct ipv4hdr * iphdr;.

But maybe this isn't even what you intended. Do you really want iphdr to be a pointer in your struct? It makes mucht more sense, if it was part of the struct, like this:

struct packet{
    struct ipv4hdr iphdr;  // notice that we do not use pointers here!
    struct icmphdr icmphdr; // this looks curious to me - we have either an IP or an ICMP package, why both headers in the same package?
    char * data;
};