/*发送三个ICMP报文*/
void send_packet()
{ int packetsize;
while( nsend<MAX_NO_PACKETS)
{ nsend++;
packetsize=pack(nsend); /*设置ICMP报头*/
if( sendto(sockfd,sendpacket,packetsize,0,
(struct sockaddr *)&dest_addr,sizeof(dest_addr) )<0 )
{ perror("sendto error");
continue;
}
sleep(1); /*每隔一秒发送一个ICMP报文*/
}
}
/*接收所有ICMP报文*/
void recv_packet()
{ int n,fromlen;
extern int errno;
signal(SIGALRM,statistics);
fromlen=sizeof(from);
while( nreceived<nsend)
{ alarm(MAX_WAIT_TIME);
if( (n=recvfrom(sockfd,recvpacket,sizeof(recvpacket),0,
(struct sockaddr *)&from,&fromlen)) <0)
{ if(errno==EINTR)continue;
perror("recvfrom error");
continue;
}
gettimeofday(&tvrecv,NULL); /*记录接收时间*/
if(unpack(recvpacket,n)==-1)continue;
nreceived++;
}
}
/*剥去ICMP报头*/
int unpack(char *buf,int len)
{ int i,iphdrlen;
struct ip *ip;
struct icmp *icmp;
struct timeval *tvsend;
double rtt;
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< /*小于ICMP报头长度则不合理*/
{ printf("ICMP packets\''s length is less than 8\n");
return -1;
}
/*确保所接收的是我所发的的ICMP的回应*/
if( (icmp->;icmp_type==ICMP_ECHOREPLY) && (icmp->;icmp_id==pid) )
{ tvsend=(struct timeval *)icmp->;icmp_data;
tv_sub(&tvrecv,tvsend); /*接收和发送的时间差*/
rtt=tvrecv.tv_sec*1000+tvrecv.tv_usec/1000; /*以毫秒为单位计算rtt*/
/*显示相关信息*/
printf("%d byte from %s: icmp_seq=%u ttl=%d rtt=%.3f ms\n",
len,
inet_ntoa(from.sin_addr),
icmp->;icmp_seq,
ip->;ip_ttl,
rtt);
}
else return -1;
}
main(int argc,char *argv)
{ struct hostent *host;
struct protoent *protocol;
unsigned long inaddr=0l;
int waittime=MAX_WAIT_TIME;
int size=50*1024;
if(argc<2)
{ printf("usage:%s hostname/IP address\n",argv[0]);
exit(1);
}
if( (protocol=getprotobyname("icmp") )==NULL)
{ perror("getprotobyname");
exit(1);
}
/*生成使用ICMP的原始套接字,这种套接字只有root才能生成*/
if( (sockfd=socket(AF_INET,SOCK_RAW,protocol->;p_proto) )<0)
{ perror("socket error");
exit(1);
}
/* 回收root权限,设置当前用户权限*/
setuid(getuid());
/*扩大套接字接收缓冲区到50K这样做主要为了减小接收缓冲区溢出的
的可能性,若无意中ping一个广播地址或多播地址,将会引来大量应答*/
setsockopt(sockfd,SOL_SOCKET,SO_RCVBUF,&size,sizeof(size) );
bzero(&dest_addr,sizeof(dest_addr));
dest_addr.sin_family=AF_INET;
/*判断是主机名还是ip地址*/
if( inaddr=inet_addr(argv)==INADDR_NONE)
{ if((host=gethostbyname(argv) )==NULL) /*是主机名*/
{ perror("gethostb