Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1052394
  • 博文数量: 836
  • 博客积分: 43880
  • 博客等级: 大将
  • 技术积分: 5485
  • 用 户 组: 普通用户
  • 注册时间: 2008-08-20 17:36
文章分类

全部博文(836)

文章存档

2011年(1)

2008年(835)

我的朋友

分类: LINUX

2008-08-20 18:24:35


如果目的主机在工输出在工状态如果5妙内无相应用SIGALRM信号中断进程

#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,sizeof(buf)))==-1)
err_sys("read");

ip=(structip*)buf;
if(ip->ip_p!=IPPROTO_ICMP){
fprintf(stderr,"protocolerror.\r\n");
exit(1);
}
icmp=(structicmp*)(buf sizeof(structip));
if(icmp->icmp_type==ICMP_ECHOREPLY){
if(icmp->icmp_id!=getpid()){
fprintf(stderr,"notthisprocess.\r\n");
exit(1);
}else{
printf("destinationhostisalive.\r\n");
break;
}
}
}
}

uint16_tin_cksum(uint16_t*addr,intlen)
{
intnleft=len;
uint32_tsum=0;
uint16_t*w=addr;
uint16_tanswer=0;

while(nleft>1){
sum =*w ;
nleft-=2;
}

if(nleft==1){
*(unsignedchar*)(&answer)=*(unsignedchar*)w;
sum =answer;
}

sum=(sum>>16) (sum&0xffff);
sum =(sum>>16);
answer=~sum;
return(answer);
}

voiderr_sys(constchar*errmsg)
{
perror(errmsg);
exit(1);
}


(责任编辑:云子)


下载本文示例代码
阅读(474) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~