2017-10-09 131 views
-1

現在我正在處理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)); 
+0

顯示更多代碼,我們不禁用3行代碼。 –

+1

我添加了icmp數據包的完整部分。 –

回答

2

如果你想創建一個packet你必須一個塊內存分配給它,而不是'子結構'。你有你有

ip=malloc(sizeof(*ip)); 
icmp=malloc(sizeof(*icmp)); 

int sock; 

uint16_t psize = sizeof(*icmp)+sizeof(*ip); 
static char *packet; 
ip= (struct iphdr*) packet;  // here you access undefined pointer packet; previous contents of ip is lost 
icmp= (struct icmphdr*)(ip+1); // same for icmp 

刪除TE malloc() S和它更改爲

---- 
static char *packet; 

packet = malloc(sizeof *ip + sizeof *icmp); 
ip= (struct iphdr*) packet; 
icmp= (struct icmphdr*)(ip+1); 
+0

謝謝,明白了。 –

2

。在你的代碼基本錯誤。

在這裏,您分配內存兩個變量

ip=malloc(sizeof(*ip)); 
icmp=malloc(sizeof(*icmp)); 

但你不久後

static char *packet; 
ip= (struct iphdr*) packet; 
icmp= (struct icmphdr*)(ip+1); 

所以ipicmp不再指向分配的內存。相反,您已將它們分配給未初始化的變量的值,即packet。這是未定義的行爲,並解釋了seg故障。

1

,當你到ipicmp分配值的問題發生。我推薦以下代碼:

struct packet { 
    struct iphdr ip; 
    struct icmphdr icmp; 
} myPacket; 

myPacket = (struct packet*)malloc(sizeof(struct packet)); 

ip =(struct iphdr*) &packet.ip; 
icmp = (struct icmphdr*) &packet.icmp;