所以,我必须做库发送IPv4数据包(没有带有准备好标头的库),问题是我无法使用函数时访问结构内部结构中的字段,尽管eclipse没有看到错误,提示没有显示这是可能的。
结构:
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;
};
指向函数的指针(这是必需的,两者都有效):
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");
创建结构包:
struct packet * createPacket(){
struct packet * pack= malloc(sizeof(struct packet));
return pack;
}
现在,在 main 中调用字段确实显示了可能的字段:
struct packet * pack = packetCreate();
pack->iphdr->(CTRL+space displays all the fields) //and eclipse automatically corrects all the . to ->
同时,在使用提示时调用函数上的创建指针不显示字段,这会导致分段错误(核心转储):
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;
}
再次问题是为什么我不能在指向原始结构的函数中调用特定字段以及如何在该函数中执行此操作
看起来您忘记为struct ipv4hdr * iphdr;
分配空间。
但也许这甚至不是你的意图。你真的希望 iphdr 成为你结构中的一个指针吗?如果它是结构的一部分,则更有意义,如下所示:
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;
};