所以,我必须做库发送IPv4数据包(没有带有准备头的库),问题是我在使用函数时无法访问struct里面的struct,虽然eclipse看不到错误,提示没有显示是可能的。
的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;
};
指示功能(这是必需的,都有效):
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:
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;
}
再次提问是为什么我不能调用指向原始结构的函数内的特定字段以及如何在该函数内执行此操作
答案 0 :(得分:0)
您似乎忘了为struct ipv4hdr * iphdr;
分配空间。
但也许这甚至不是你想要的。你真的希望iphdr成为你结构中的指针吗?如果它是结构的 part ,那就更有意义了,如下所示:
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;
};