复习用 /* * THIS FILE IS FOR IP FORWARD TEST */ #include "sysInclude.h" #include <vector> using std::vector; // system support extern void fwd_LocalRcv(char *pBuffer, int length); extern void fwd_SendtoLower(char *pBuffer, int length, unsigned int nexthop); extern void fwd_DiscardPkt(char *pBuffer, int type); extern unsigned int getIpv4Address( ); // implemented by students //一个路由节点 struct route_table { int dest; int nexthop; }; //路由表 vector<route_table> mytable; void stud_Route_Init() { return; } // 添加函数就是从proute中取出dest和nexthop,构成一个路由节点,然后加入路由表 void stud_route_add(stud_route_msg *proute) { int dest; route_table t; dest = ntohl(proute->dest) & ((1<<31)>>(ntohl(proute->masklen)-1)); t.dest = dest; t.nexthop = ntohl(proute->nexthop); mytable.push_back(t); return; } int stud_fwd_deal(char *pBuffer, int length) { int version = pBuffer[0] >> 4; int headlength = pBuffer[0] & 0xf; int timetolive = (int)pBuffer[8]; int headerChecksum = ntohs(*(short unsigned int*)(pBuffer+10)); int destinationAddress = ntohl(*(unsigned int*)(pBuffer+16)); if (destinationAddress == getIpv4Address()) //destination地址和本机地址相同 { //调用fwd_LocalRcv把ip包交给上层协议函数 fwd_LocalRcv(pBuffer,length); return 0; } if (timetolive <= 0) //TTL小于等于0时丢弃该包 { fwd_DiscardPkt(pBuffer,STUD_FORWARD_TEST_TTLERROR); return 1; } vector<route_table>::iterator ii; for (ii = mytable.begin(); ii!=mytable.end(); ii++) //在路由表中查找下一跳地址 { if (ii->dest == destinationAddress) //如果能找到 { char *buffer = new char[length]; memcpy(buffer,pBuffer,length); buffer[8]--; int sum = 0; //重新计算校验和 unsigned short int localCheckSum = 0; for(int i = 0;i < 2 * headlength;i ++) { if (i == 5) continue; sum = sum + (buffer[i*2]<<8) + (buffer[i*2+1]); sum %= 65535; } localCheckSum = htons(0xffff - (unsigned short int)sum); memcpy(buffer+10, &localCheckSum, sizeof(short unsigned int)); fwd_SendtoLower(buffer, length, ii->nexthop); //发送至下一跳 return 0; } } fwd_DiscardPkt(pBuffer,STUD_FORWARD_TEST_NOROUTE); //路由表中不存在下一跳,丢弃该包 return 1; }