Chinaunix首页 | 论坛 | 博客
  • 博客访问: 453494
  • 博文数量: 70
  • 博客积分: 3170
  • 博客等级: 中校
  • 技术积分: 756
  • 用 户 组: 普通用户
  • 注册时间: 2007-06-06 16:47
文章分类

全部博文(70)

文章存档

2011年(22)

2010年(33)

2009年(5)

2008年(10)

分类: C/C++

2010-11-30 15:30:39

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define MAX_WAIT_TIME 1
#define PACKET_SIZE        4096
#define DATA_LEN            56
struct sockaddr_in gg_dest_addr;
static unsigned int gg_icmp_seq;
static void tv_sub(struct timeval *out,struct timeval *in){
    if( (out->tv_usec-=in->tv_usec)<0){
            --out->tv_sec;
          out->tv_usec+=1000000;
        }
       out->tv_sec-=in->tv_sec;
}
static unsigned short cal_chksum(unsigned short *addr,int len){
    int nleft=len;
    int sum=0;
    unsigned short *w=addr;
    unsigned short answer=0;

    /*把ICMP报头二进制数据以2字节为单位累加起来*/
    while(nleft>1){
        sum+=*w++;
        nleft-=2;
    }
    /*若ICMP报头为奇数个字节,会剩下最后一字节。把最后一个字节视为一个2字节数据的高字节,这个2字节数据的低字节为0,继续累加*/
    if( nleft==1){
        *(unsigned char *)(&answer)=*(unsigned char *)w;
        sum+=answer;
    }
    sum=(sum>>16)+(sum&0xffff);
    sum+=(sum>>16);
    answer=~sum;
    return answer;
}

static int pack( char *sendpacket ){
    int packsize;
    struct icmp *icmp;
    struct timeval *tval;
    icmp=(struct icmp*)sendpacket;
    icmp->icmp_type=ICMP_ECHO;
    icmp->icmp_code=0;
    icmp->icmp_cksum=0;
    icmp->icmp_seq=++gg_icmp_seq;
    icmp->icmp_id=getpid();
    packsize=8+DATA_LEN;
    tval= (struct timeval *)icmp->icmp_data;
    gettimeofday(tval,(struct timezone *)NULL);     /*记录发送时间*/
    icmp->icmp_cksum=cal_chksum( (unsigned short *)icmp,packsize);   /*校验算法*/
    return packsize;
}

static int  send_packet(int sockfd){
    int packetsize;
    char sendpacket[64];
    packetsize=pack(sendpacket); /*设置ICMP报头*/
    if( sendto(sockfd,sendpacket,packetsize,0,
              (struct sockaddr *)&gg_dest_addr,sizeof(gg_dest_addr) )<0  ){
                  printf("errno:[%d],errmsg:[%s]\n",errno,strerror(errno));
            return -1;
    }
    return 0;

}
static int unpack(char *buf,struct icmp **icmp,struct sockaddr_in *from,struct sockaddr_in *dest_addr,unsigned *ttl,int len){
    struct ip *ip;
    int iphdrlen;

    ip=(struct ip *)buf;
    iphdrlen=ip->ip_hl<<2;    /*求ip报头长度,即ip报头的长度标志乘4*/
    *icmp=(struct icmp *)(buf+iphdrlen);  /*越过ip报头,指向ICMP报头*/
    len-=iphdrlen;            /*ICMP报头及ICMP数据报的总长度*/
    if( len<8)                /*小于ICMP报头长度则不合理*/{
        printf("ICMP packets\'s length is less than 8\n");
        return -1;
    }
    /*确保所接收的是我所发的的ICMP的回应*/
    if( (((*icmp)->icmp_type!=ICMP_ECHOREPLY) && ((*icmp)->icmp_type!=ICMP_ECHO) ) || ((*icmp)->icmp_id!=getpid()) ||
                ((*icmp)->icmp_seq != gg_icmp_seq)
                || (from->sin_addr.s_addr != dest_addr->sin_addr.s_addr)){
         return -1;
    }
    *ttl = ((struct iphdr *)buf)->ttl;
    return 0;
}

static int recv_packet(int sockfd,unsigned int *mrtt,unsigned int *urtt,unsigned int *ttl,struct sockaddr_in *from,struct sockaddr_in *dest_addr){
    struct timeval tvrecv;
    struct timeval *tvsend;
    struct icmp *icmp;

    int n;
    socklen_t fromlen;

    char recvpacket[PACKET_SIZE];

    fromlen=sizeof(struct sockaddr_in);
    if( (n=recvfrom(sockfd,recvpacket,sizeof(recvpacket),0,(struct sockaddr *)from,&fromlen)) <0){
        return -1;
    }
    gettimeofday(&tvrecv,NULL);  /*记录接收时间*/

    if(unpack(recvpacket,&icmp,from,dest_addr,ttl,n)==-1){
        printf("recv_packet error 2\n");
        return -2;
    }
    tvsend=(struct timeval *)icmp->icmp_data;
    tv_sub(&tvrecv,tvsend);  /*接收和发送的时间差*/
    *mrtt=tvrecv.tv_sec*1000+tvrecv.tv_usec/1000;
    *urtt=tvrecv.tv_usec%1000;
     /*以毫秒为单位计算rtt*/
    return 0;
}

static int ping(char *ip,unsigned int *mrtt,unsigned int *urtt,unsigned int *ttl){
    struct hostent *host;
    struct protoent *protocol;
    struct sockaddr_in from;
    struct timeval begin_recv;
    struct timeval end_recv;
    unsigned long inaddr=0l;
    int result = 0;
    int sockfd;
    if( (protocol=getprotobyname("icmp") )==NULL){
        perror("getprotobyname");
        return -1;
    }
    /*生成使用ICMP的原始套接字,这种套接字只有root才能生成*/
    if( (sockfd=socket(AF_INET,SOCK_RAW,protocol->p_proto) )<0){
        perror("socket error");
        return -1;
    }
    struct timeval var;
    var.tv_sec = MAX_WAIT_TIME; //the second is 5
    var.tv_usec = 0; //the 0
    if (setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &var,
            sizeof(struct timeval)) == 0) {
        //printf("var [%lu] [%lu] len [%d]\n", var.tv_sec,var.tv_usec, len);
    } else {
        perror("setsockopt err");
        close(sockfd);
        return -1;
    }
    /*扩大套接字接收缓冲区到50K这样做主要为了减小接收缓冲区溢出的
          的可能性,若无意中ping一个广播地址或多播地址,将会引来大量应答*/
    memset(&gg_dest_addr,0,sizeof(gg_dest_addr));
    gg_dest_addr.sin_family=AF_INET;
    /*判断是主机名还是ip地址*/
    if( (inaddr=inet_addr(ip))==INADDR_NONE){
        if((host=gethostbyname(ip) )==NULL) /*是主机名*/{
            perror("gethostbyname error");
            close(sockfd);
            return -1;
        }
       memcpy( (char *)&gg_dest_addr.sin_addr,host->h_addr,host->h_length);
    }
    else{    /*是ip地址*/
        gg_dest_addr.sin_addr.s_addr = inet_addr(ip);
//        memcpy( (char *)&gg_dest_addr,(char *)&inaddr,host->h_length);
    }
    /*获取main的进程id,用于设置ICMP的标志符*/
    result = send_packet(sockfd);  /*发所有ICMP报文*/
    if (result < 0) {
        close(sockfd);
        return result;
    }
    gettimeofday(&begin_recv,NULL);
    do{
        result = recv_packet(sockfd,mrtt,urtt,ttl,&from,&gg_dest_addr);  /*接收所有ICMP报文*/
        gettimeofday(&end_recv,NULL);
    }while( (-2 == result) &&  (*mrtt < 1));
    close(sockfd);
    return result;
}
int main(int argc,char *argv[]){
    unsigned int mrtt = 0;
    unsigned int urtt = 0;
    unsigned int ttl = 0;
    char dest_ip[20]={0};
    strcpy(dest_ip,argv[1]);
    ping(dest_ip,&mrtt,&urtt,&ttl) ;
    printf("64 bytes from %s: ttl=%u time=%u.%03u ms",dest_ip,ttl,mrtt,urtt);
}

阅读(968) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2010-12-01 15:19:46

很好的, 收藏了 推荐一个博客,提供很多免费软件编程电子书下载: http://free-ebooks.appspot.com