我编写了一个C
程序来发送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
请告诉我我错过了什么..谢谢。
答案 0 :(得分:2)
I->msg
的尺寸仅为20
,但您设置的容量超过其容量:
memset(I->msg, 0, 100); // 100 > 20 and it exceeds the array boundaries