当前位置: 技术问答>linux和unix
linux下ping代码出错
来源: 互联网 发布时间:2016-04-26
本文导语: 最近编写了一个linux下实现ping功能的程序,但是在测试时icmp数据包总是阻塞在recvfrom函数中,不知道是什么原因,各位高人请指教。发生错误的相关代码如下: for(;;) { register size; register u_ch...
最近编写了一个linux下实现ping功能的程序,但是在测试时icmp数据包总是阻塞在recvfrom函数中,不知道是什么原因,各位高人请指教。发生错误的相关代码如下:
for(;;)
{
register size;
register u_char ttl;
register delta;
register iIpHeadLen;
ping();
fprintf(stderr,"after ping()n");
size=recvfrom(sock,buf,sizeof(buf),0,(struct sockaddr *)&it,&namelen);
fprintf(stderr,"after recvfromn");//程序总是返回该调试信息,而不会向下运行。
if(size==-1 && errno==EINTR)
{
continue;
}
delta=(int)((time_now()-lSendTime)/1000);
pIpHead=(IPHEAD*)buf;
iIpHeadLen=(int)((pIpHead->ip_verlen&0x0f)icmp_type!=ICMP_ECHOREPLY)
{
continue;
}*/
if(pIcmpHead->icmp_id!=seq||pIcmpHead->icmp_seq!=seq)
{
fprintf(stderr,"i will continue for ICMPHEAD->idn");
continue;
}
sprintf(buf,"icmp_seq=%u bytes=%d ttl=%d",pIcmpHead->icmp_seq,size,ttl);
fprintf(stderr,"reply from %s:%s time=%d msn",host,buf,delta);
max=MAX(delta,max);
min=min?MIN(delta,min):delta;
total+=delta;
++recvd;
++seq;
}
}
ping()主要负责使用sendto来发送icmp数据包,如下:
ping()
{
char buf[200];
int iPacketSize;
ICMPHEAD *pIcmpHead=(ICMPHEAD*)buf;
pIcmpHead->icmp_type=ICMP_ECHO;
pIcmpHead->icmp_code=0;
pIcmpHead->icmp_id=seq;
pIcmpHead->icmp_seq=seq;
pIcmpHead->icmp_chksum=0;
//fprintf(stderr,"1n");
*((long*)pIcmpHead->icmp_data)=time_now();
iPacketSize=ICMP_HEADSIZE+4;
pIcmpHead->icmp_chksum=ChkSum((u_short*)pIcmpHead,iPacketSize);
lSendTime=time_now();
if(sendto(sock,buf,iPacketSize,0,(struct sockaddr*)&it,sizeof(it))
for(;;)
{
register size;
register u_char ttl;
register delta;
register iIpHeadLen;
ping();
fprintf(stderr,"after ping()n");
size=recvfrom(sock,buf,sizeof(buf),0,(struct sockaddr *)&it,&namelen);
fprintf(stderr,"after recvfromn");//程序总是返回该调试信息,而不会向下运行。
if(size==-1 && errno==EINTR)
{
continue;
}
delta=(int)((time_now()-lSendTime)/1000);
pIpHead=(IPHEAD*)buf;
iIpHeadLen=(int)((pIpHead->ip_verlen&0x0f)icmp_type!=ICMP_ECHOREPLY)
{
continue;
}*/
if(pIcmpHead->icmp_id!=seq||pIcmpHead->icmp_seq!=seq)
{
fprintf(stderr,"i will continue for ICMPHEAD->idn");
continue;
}
sprintf(buf,"icmp_seq=%u bytes=%d ttl=%d",pIcmpHead->icmp_seq,size,ttl);
fprintf(stderr,"reply from %s:%s time=%d msn",host,buf,delta);
max=MAX(delta,max);
min=min?MIN(delta,min):delta;
total+=delta;
++recvd;
++seq;
}
}
ping()主要负责使用sendto来发送icmp数据包,如下:
ping()
{
char buf[200];
int iPacketSize;
ICMPHEAD *pIcmpHead=(ICMPHEAD*)buf;
pIcmpHead->icmp_type=ICMP_ECHO;
pIcmpHead->icmp_code=0;
pIcmpHead->icmp_id=seq;
pIcmpHead->icmp_seq=seq;
pIcmpHead->icmp_chksum=0;
//fprintf(stderr,"1n");
*((long*)pIcmpHead->icmp_data)=time_now();
iPacketSize=ICMP_HEADSIZE+4;
pIcmpHead->icmp_chksum=ChkSum((u_short*)pIcmpHead,iPacketSize);
lSendTime=time_now();
if(sendto(sock,buf,iPacketSize,0,(struct sockaddr*)&it,sizeof(it))