网络编程之ping

时间:2022-11-21 22:17:20

#include <sys/types.h>
#include <netinet/ip.h>
#include <netdb.h>
#include<arpa/inet.h>
#include <errno.h>
#include <netinet/ip_icmp.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <signal.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <netdb.h>
#include <setjmp.h>
#include <errno.h>
unsigned short cal_chksum(unsigned short *addr,int len)
{       int nleft=len;
        int sum=0;
        unsigned short *w=addr;
        unsigned short answer=0;
        while(nleft>1)
        {       sum+=*w++;
                nleft-=2;
        }
        if( nleft==1)
        {       *(unsigned char *)(&answer)=*(unsigned char *)w;
                sum+=answer;
        }
        sum=(sum>>16)+(sum&0xffff);
        sum+=(sum>>16);
        answer=~sum;
        return answer;
}
int main(int argc, char **argv)
{
 if(argc < 2)
{
printf("you input arg is less than two\n");
}
   struct sockaddr_in serveraddr;
   int sockfd = 0;
   if((sockfd = socket(AF_INET,SOCK_RAW,IPPROTO_ICMP)) <0 )
   {
      printf("error\n");
   }
   printf("sockfd is %d\n",sockfd);
   bzero(&serveraddr,sizeof(serveraddr));
   serveraddr.sin_family = AF_INET;
   serveraddr.sin_port = htons(0);
//   char arg[] = "192.168.1.150";
   inet_pton(AF_INET,argv[1],&serveraddr.sin_addr);
   char sendpack[1024] = {0};

struct icmp *picmp = NULL;
   picmp = (struct icmp*)sendpack;
   picmp->icmp_type = ICMP_ECHO;
   picmp->icmp_code = 0;
   picmp->icmp_cksum=0;
   picmp->icmp_seq=0;
   picmp->icmp_id=getpid();
   picmp->icmp_cksum=cal_chksum( (unsigned short *)picmp,64);
   errno = 0;
  // int num = 2;
   int n = 0;
   double rtt;
   struct ip *piphead;
   struct timeval tvsend,tvrecv;
   char recvbuff[4096] = {0};
   struct sockaddr_in addrfrom;
   int len =  sizeof(addrfrom);
   while(1)
   {

//tvsend = (struct timeval *)picmp->icmp_data;
     gettimeofday(&tvsend,NULL);
     if(( n = sendto(sockfd,sendpack,64,0,(struct sockaddr*)&serveraddr,sizeof(serveraddr))) == -1)
     {      
        perror("sendto error\n");
     }
     sleep(1);
     if((recvfrom(sockfd, recvbuff, sizeof(recvbuff), 0, (struct sockaddr*)&addrfrom,&len)) < 0)
     {
       printf("error");
     }
     gettimeofday(&tvrecv,NULL);
     rtt = 1000 * (tvrecv.tv_sec - tvsend.tv_sec) + (tvrecv.tv_usec - tvsend.tv_usec)/1000;
     printf("recvform %s : rtt = %.3fms\n",inet_ntoa(addrfrom.sin_addr),rtt);
   }
   return 0;

}