51單片機簡單Ping的實現(xiàn)
PingEcho(*輸入包緩沖區(qū)首址pBUF) //收到應答后回顯{ //打印ping響應,因為51定時器較慢,time參數(shù)省略(time是本機與對方主機往返一次所用時間)。 PrintStr("\tReply from IP="); PrintStr(輸入包之源IP地址); PrintStr(": bytes=32"); PrintStr(" TTL="); PrintByte(輸入包之TTL); PrintStr(""); //處理PingBuf的記錄 for(i=0;iMaxLenPingBuf;i++){ if(PingBuf[i].status==1){ if(PingBuf[i].ip==pBUF.ipframe.ip){ PingBuf[i].status=2; //已發(fā)出且應答 break; } } }}
PingCycle() //定時操作,放在1秒循環(huán)任務中{ for(;;){ taskDelay(1秒); for(i=0;iMaxLenPingBuf;i++){ switch(PingBuf[i].status) case 0: //空閑 break; { case 1: //已發(fā)出但無應答 //打印超時信息 PrintStr("\tRequest timed out.("); PrintStr(PingBuf[i].ip); PrintStr(")"); case 2: //已發(fā)出且應答 //狀態(tài)變遷 PingBuf[i].times=PingBuf[i].times-1; if(PingBuf[i].times==0) PingBuf[i].status=0; else{ case 4: //第一次準備發(fā)(用于同步1秒時鐘) //查ARP緩存 if(ARP緩存有對應項){ //直接發(fā)送ICMP包至TxQFIFO緩存 OSQSend(QID,*pBUF); PingBuf[i].status=1; //已發(fā)出但無應答 } else PingBuf[i].status=3; //等ARP } break; } case 3: //等ARP { //查ARP緩存 if(ARP緩存有對應項){ //直接發(fā)送ICMP包至TxQFIFO緩存 OSQSend(QID,*pBUF); } PingBuf[i].status=1; //已發(fā)出但無應答 } default: //其他狀態(tài),錯誤 PingBuf[i].status=0; } }}
void PingCommand(WORDTABLE *WordTable)//PING命令處理{ if(WordTable->Num==1) PrintStr("Please input IP address!"); else{ if(IPadrToHEX(WordTable->wt[1].Str,ping_ip_address)==0){ PrintStr("IP address error!");return; } else PingRequest(ping_ip_address); }}
INT16U CheckSum(INT16U *buf,INT16U length) //校驗和計算{ INT16U len; INT32U sum; len=length>>1; for(sum=0;len>0;len--) sum+=*buf++; if(length1) sum+=(*buf0xFF00); sum=(sum>>16)+(sum0xFFFF); sum+=(sum>>16); return(~sum);}
union ip_address_type{ //ip地址數(shù)據(jù)結(jié)構(gòu)unsigned long dwords;unsigned int words[2];unsigned char bytes[4];};
bit IPadrToHEX(unsigned char *Str,union ip_address_type *ip) //IP字符串轉(zhuǎn)換到IP地址值{ unsigned char i,j,ch,x;
ch=*Str++;
for(j=0;j3;j++){ x=0; for(i=0;i4;i++){ if(ch==".") {ch=*Str++;break;} else if(i==3) return 0; else if(ch0ch>9) return 0; else x=10*x+(ch-"0"); ch=*Str++; } ip->bytes[j]=x; }
x=0; for(i=0;i4;i++){ if(ch=="\0") {ch=*Str++;break;} else if(i==3) return 0; else if(ch0ch>9) return 0; else x=10*x+(ch-"0"); ch=*Str++; } ip->bytes[3]=x; return 1;}
void HEXToIPadr(unsigned char *Str,union ip_address_type *ip) //IP地址值轉(zhuǎn)換到IP字符串{ unsigned char i; unsigned char x,y;
for(i=0;i4;i++){ x=ip->bytes[i]; if(x>99){ y=x/100;*Str++=y+"0"; x=x-100*y;y=x/10;*Str++=y+"0"; x=x-10*y;*Str++=x+"0"; if(i==3) *Str++="\0"; else *Str++="."; } else if(x>9){ y=x/10;*Str++=y+"0"; x=x-10*y;*Str++=x+"0"; if(i==3) *Str++="\0"; else *Str++="."; } else{ *Str++=x+"0"; if(i==3) *Str++="\0"; else *Str++="."; } }}
參考文獻:1?!队肨CP/IP進行網(wǎng)際互連》(第3版)