分类: LINUX
2008-08-20 18:24:35
#include"unp.h"
voidsend_echo_req(intsockfd,structsockaddr_in*dstaddr);
uint16_tin_cksum(uint16_t*addr,intlen);
voidrecv_echo_reply(intsockfd);
intmain(intargc,char**argv)
{
intsockfd;
structsockaddr_indstaddr;
if((sockfd=socket(PF_INET,SOCK_RAW,IPPROTO_ICMP))==-1)
err_sys("socket");
bzero(&dstaddr,sizeof(dstaddr));
dstaddr.sin_family=AF_INET;
dstaddr.sin_port=htons(0);
if(inet_pton(AF_INET,argv[1],&dstaddr.sin_addr)<=0)
err_sys("inet_pton");
send_echo_req(sockfd,&dstaddr);
recv_echo_reply(sockfd);
exit(0);
}
voidsend_echo_req(intsockfd,structsockaddr_in*dstaddr)
{
charbuf[100];
size_tlen=sizeof(structicmp);
structicmp*icmp;
socklen_tdstlen=sizeof(structsockaddr_in);
bzero(buf,sizeof(buf));
icmp=(structicmp*)buf;
icmp->icmp_type=ICMP_ECHO;
icmp->icmp_code=0;
icmp->icmp_id=getpid();
icmp->icmp_seq=1;
icmp->icmp_cksum=in_cksum((uint16_t*)icmp,sizeof(structicmp));
if(sendto(sockfd,buf,len,0,(SA*)dstaddr,dstlen)==-1)
err_sys("sendto");
}
voidrecv_echo_reply(intsockfd)
{
charbuf[100];
ssize_tn;
structip*ip;
structicmp*icmp;
while(1){
alarm(5);/*settimeout*/
if((n=read(sockfd,buf