if(!nRet)
{
printf("\nTimeOut");//输出超时提示
break;
}
//接收应答
dwTimeSent=RecvEchoReply(rawSocket,&saSrc,&cTTL);//计算传输时间
dwElapsed=GetTickCount()-dwTimeSent;
printf("\nReply from:%s:bytes=%d time =%ld ms TTL=%d",
inet_ntoa(saSrc.sin_addr),REQ_DATASIZE,dwElapsed,cTTL);
printf("\n");
}
nRet=closesocket(rawSocket);
if(nRet==SOCKET_ERROR)
{
ReportError("closesocket()");
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
int SendEchoRequest(SOCKET s,LPSOCKADDR_IN lpstToAddr)//给目标站点发送回送请求
{
static ECHOREQUEST echoReq;
static 751com.cn
int nRet;
//填写回送请求信息
echoReq.icmpHdr.Type=ICMP_ECHOREQ;
echoReq.icmpHdr.Code=0;
echoReq.icmpHdr.Checksum=0;
echoReq.icmpHdr.ID=nId++;
echoReq.icmpHdr.Seq=nSeq++;
//填写要发送的数据
for(nRet=0;nRet<REQ_DATASIZE;nRet++)
echoReq.cData[nRet]=' '+nRet;//保存发送时间
echoReq.dwTime=GetTickCount();//数据存入包中并计算检验和
echoReq.icmpHdr.Checksum=in_cksum((u_short*)&echoReq,sizeof(ECHOREQUEST));//发送回送请求
int nAddrLen=sizeof(struct sockaddr_in);
nRet=sendto(s,(LPSTR)&echoReq,sizeof(ECHOREQUEST),0,(LPSOCKADDR)lpstToAddr,nAddrLen);
if(nRet==SOCKET_ERROR)
ReportError("sendto()");
return(nRet);
}
//接收数据并对字段进行分析
DWORD RecvEchoReply(SOCKET s,LPSOCKADDR_IN lpsaFrom,u_char *pTTL)
{
ECHOREPLY echoReply;
int nRet;
int nAddrLen=sizeof(struct sockaddr_in);//接收回送应答
nRet=recvfrom(s,(LPSTR)&echoReply,sizeof(ECHOREPLY),0,(LPSOCKADDR)lpsaFrom,&nAddrLen);//检查返回值
if(nRet==SOCKET_ERROR)
ReportError("recvform()");
*pTTL=echoReply.ipHdr.TTL;//返回发送时间的IP生存时间TTL
return(echoReply.echoRequest.dwTime);
}
//输出发生的错误
void ReportError(LPCSTR pWhere)
{
fprintf(stderr,"\n error:%d\n",WSAGetLastError());
}
//使用select()函数进行状态查询,以确定是否有数据等待读取
int WaitForEchoReply(SOCKET s)
{
struct timeval Timeout;
fd_set readfds;
readfds.fd_count=1;
readfds.fd_array[0]=s;
Timeout.tv_sec=5;
Timeout.tv_usec=0;
751com.cn
register u_short answer;
register int sum=0;
while(nleft>1)
{
sum+=*w++;
nleft-=2;
}
if(nleft==1)
{
u_short u=0;
*(u_char*)(&u)=*(u_char*)w;
sum+=u;
}
sum=(sum>>16)+(sum&0xffff);
sum+=(sum>>16);
answer=~sum;
return(answer);
}