Question

I have written a C program to send an ICMP packet. Here is the corresponding code..

#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;
}

The problem with the code is that when I run it, the icmp packet is successfully sent which i can see in wire shark. But at last after displaying sent successfully i get the following error..

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

Please tell me what am I missing..Thanks.

Was it helpful?

Solution

Size of I->msg is just 20, but you're setting more than its capacity:

memset(I->msg, 0, 100); // 100 > 20 and it exceeds the array boundaries 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top