2013-03-20 74 views
0

我寫了一個C程序發送一個ICMP數據包。下面是相應的代碼..堆棧粉碎detect..while發送ICMP包

#include <sys/types.h> 
#include <sys/socket.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <netinet/in.h> 
#include <arpa/inet.h> 
#include <string.h> 
#include <netdb.h> 

int Seq_Num = 1; 
struct icmp_header 
{ 
unsigned char type; 
unsigned char code; 
unsigned short check_sum; 
unsigned short id; 
unsigned short seq_num; 
char msg[20]; 
    }; 

void make_icmp(struct icmp_header *I, char *msg_to_snd, int m_len) 
{ 
I->type = 13; //for timestamp 
I->code = 0; // request.. 
I->id = htons(713); //some unique ID.. 
I->seq_num= htons(Seq_Num); 
Seq_Num++; 
/*computing the check sum..*/ 
unsigned int Sum = 0; 
memset(I->msg, 0, 100); 
unsigned short *ptr = (unsigned short*)I; 
Sum += *ptr++; 
ptr++; 
Sum += *ptr++; 
Sum += *ptr++; 
strcpy(I->msg, msg_to_snd); 

ptr = (unsigned short*)I->msg; 

int len = m_len; 
if(len & 1) 
    len++; 

while(len >=0) 
{ 
    Sum += *ptr++; 
    len -=2; 
} 

Sum = (Sum >>16) + Sum& 0x0000ffff; /*add the carries..*/ 

Sum += (Sum>>16); /*add the newly generated carries..*/ 

I->check_sum = ~Sum;  
} 

int main(int argc, char* argv[]) 
{ 
if(argc ==1) 
{ 
    perror("ip addr. required..\n"); 
    exit(1); 
} 


    int sock = socket(AF_INET, SOCK_RAW, 1); 

    if(sock==-1) 
    { 
     perror("sock():"); 
     exit(1); 
    } 

    struct sockaddr_in Sk; 
    bzero(&Sk, sizeof(Sk)); 
    Sk.sin_family = AF_INET; 
    inet_pton(AF_INET, argv[1], &Sk.sin_addr); 
    struct icmp_header Q; 


     char buf[20]; 
     scanf("%s", buf); 
     make_icmp(&Q, buf, strlen(buf));  

     if(sendto(sock, &Q, sizeof(Q), 0, (struct sockaddr*)&Sk, sizeof(Sk))<0) 
     { 
      perror("sendto.."); 
      exit(1); 
     } 
     sleep(1); 
    printf("sent successfully\n"); 


return 0; 
} 

與代碼的問題是,當我運行它,ICMP報文發送成功,我可以在wire shark看到。但顯示sent successfully後,我終於收到以下錯誤..

*** stack smashing detected ***: ./a.out terminated 

請告訴我,我是什麼missing..Thanks。

+0

你在哪裏看到這樣的命名約定'icmp_header * I'? – 2014-04-24 16:33:49

回答

2

I->msg大小剛好20,但你比設定其容量更多:

memset(I->msg, 0, 100); // 100 > 20 and it exceeds the array boundaries 
+0

那麼爲什麼它沒有出現在該指令本身?它如何成功執行? – nitish712 2013-03-20 10:06:22

+0

它是未定義的行爲,有時它運行正常,有時會崩潰。 – deepmax 2013-03-20 10:07:12

+0

ohk ..非常感謝.. .. :) – nitish712 2013-03-20 10:07:45