作者:souroot 来源:WEB DNA
连接:http://www.cnblogs.com/souroot/archive/2013/05/04/3059996.html
关键词:TCPIP UIP 51单片机 计算机网络 网络工程专业 手把手教你写tcpip协议栈
版权: Q college 版权所有
=====================以下为正文=====================
先给个PC ping通单片机的效果图:
单片机ip地址:192.168.0.123
网关地址:192.168.0.1
背后的图片是串口连接的单片机,单片机收到ICMP请求后,会发送ICMP应答,我们在此在串口打印"This is STC51. We send ICMP reply!"
==============IP + ICMP报文结构体============
只对 ICMP request(echo) 进行响应,其他ICMP报文全部丢弃:
1 /* ICMP echo (i.e., ping) processing. This is simple, we only change 2 the ICMP type from ECHO to ECHO_REPLY and adjust the ICMP 3 checksum before we return the packet. */ 4 if(ICMPBUF->type != ICMP_ECHO) { 5 UIP_STAT(++uip_stat.icmp.drop); 6 UIP_STAT(++uip_stat.icmp.typeerr); 7 UIP_LOG("icmp: not icmp echo."); 8 goto drop; 9 }
然后做三件事:把ICMP报文类型改成ICMP应答,修改ICMP校验和,互换目的IP和源IP,就可以发送出去了:
1 ICMPBUF->type = ICMP_ECHO_REPLY; /* 把报文改成ICMP应答(reply) */ 2 3 /* 修改校验和 */ 4 if(ICMPBUF->icmpchksum >= HTONS(0xffff - (ICMP_ECHO << 8))) { 5 ICMPBUF->icmpchksum += HTONS(ICMP_ECHO << 8) + 1; 6 } else { 7 ICMPBUF->icmpchksum += HTONS(ICMP_ECHO << 8); 8 } 9 10 /* Swap IP addresses. */ 11 tmp16 = BUF->destipaddr[0]; 12 BUF->destipaddr[0] = BUF->srcipaddr[0]; 13 BUF->srcipaddr[0] = tmp16; 14 tmp16 = BUF->destipaddr[1]; 15 BUF->destipaddr[1] = BUF->srcipaddr[1]; 16 BUF->srcipaddr[1] = tmp16; 17 18 UIP_STAT(++uip_stat.icmp.sent); 19 20 goto send;