現在我正在處理c上的數據包,我已經成功創建了icmp數據包發送,但是我沒有辦法將它自己放入套接字中,所以我發現了多個應執行類似操作的代碼。所以他們都包含我完全不瞭解的部分,我找不到任何有關它的信息。他們正在鑄造結構與數據包到一個字符指針,如下所示:對指針施放結構
static char *packet;
ip= (struct iphdr*) packet;
icmp= (struct icmphdr*)(ip+1);
當我試過這個時,我得到了分段錯誤。請向我解釋鑄造結構的目的,以及爲什麼同一段代碼在我的情況下不起作用。謝謝。
EDITED
struct iphdr *ip;
struct icmphdr *icmp;
ip=malloc(sizeof(*ip));
icmp=malloc(sizeof(*icmp));
int sock;
uint16_t psize = sizeof(*icmp)+sizeof(*ip);
static char *packet;
ip= (struct iphdr*) packet;
icmp= (struct icmphdr*)(ip+1);
unsigned int id = (unsigned int)rand();
unsigned int seq = (unsigned int)rand();
ip->version = 4;
ip->ihl = 5;
ip->tos = 0;
ip->tot_len = htons(psize);
ip->id = id;
ip->frag_off = 0;
ip->ttl = 255;
ip->protocol = IPPROTO_ICMP;
ip->saddr = subnet.ipDec;
icmp->type = 8;
icmp->code = 0;
icmp->un.echo.id=id;
icmp->un.echo.sequence=seq;
icmp->checksum=0;
sock=socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
struct sockaddr_in destIP;
destIP.sin_family=AF_INET;
uint32_t destIPDec=0;
ip->daddr = destIPDec;
destIP.sin_addr.s_addr=destIPDec;
sendto(sock, packet, psize, 0, (struct sockaddr*) &destIP, sizeof(destIP));
顯示更多代碼,我們不禁用3行代碼。 –
我添加了icmp數據包的完整部分。 –