51单片机简单Ping的实现
PingEcho(*输入包缓冲区首址pBUF) //收到应答后回显
{
//打印ping响应,因为51定时器较慢,time参数省略(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; //已发出且应答
break;
}
}
}
}
PingCycle() //定时操作,放在1秒循环任务中
{
for(;;){
taskDelay(1秒);
for(i=0;iMaxLenPingBuf;i++){
switch(PingBuf[i].status)
case 0: //空闲
break;
{
case 1: //已发出但无应答
//打印超时信息
PrintStr("tRequest timed out.(");
PrintStr(PingBuf[i].ip);
PrintStr(")");
case 2: //已发出且应答
//状态变迁
PingBuf[i].times=PingBuf[i].times-1;
if(PingBuf[i].times==0)
PingBuf[i].status=0;
else{
case 4: //第一次准备发(用于同步1秒时钟)
//查ARP缓存
if(ARP缓存有对应项){
//直接发送ICMP包至TxQFIFO缓存
OSQSend(QID,*pBUF);
PingBuf[i].status=1; //已发出但无应答
}
else PingBuf[i].status=3; //等ARP
}
break;
}
case 3: //等ARP
{
//查ARP缓存
if(ARP缓存有对应项){
//直接发送ICMP包至TxQFIFO缓存
OSQSend(QID,*pBUF);
}
PingBuf[i].status=1; //已发出但无应答
}
default: //其他状态,错误
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地址数据结构
unsigned long dwords;
unsigned int words[2];
unsigned char bytes[4];
};
bit IPadrToHEX(unsigned char *Str,union ip_address_type *ip) //IP字符串转换到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==' ') {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地址值转换到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++=' ';
else *Str++='.';
}
else if(x>9){
y=x/10;*Str++=y+'0';
x=x-10*y;*Str++=x+'0';
if(i==3) *Str++=' ';
else *Str++='.';
}
else{
*Str++=x+'0';
if(i==3) *Str++=' ';
else *Str++='.';
}
}
}
参考文献:
1。《用TCP/IP进行网际互连》(第3版)
51单片机相关文章:51单片机教程
单片机相关文章:单片机教程
单片机相关文章:单片机视频教程
单片机相关文章:单片机工作原理
路由器相关文章:路由器工作原理
tcp/ip相关文章:tcp/ip是什么
路由器相关文章:路由器工作原理
评论