2011年的最后一晚,写篇博文纪念下。
算法描述如下:
自学习:当网桥收到一转发帧时,先查找自己的转发表中是否有源地址,若没有则添加此项。
转发帧:查找自己转发表中是否有目的地址,若没有则将此帧从其他端口转发出去。
若有,则将转发表中记录的目的地址端口和此帧进入网桥时通过的端口进行比较,若相等则丢弃此帧(因为目的主机已经收到此帧了),若不相等,则将此帧通过转发表记录的目的地址端口转发出去。
源码如下:(此代码在突出算法思想的情况下设计的尽量简单,有的情况没有考虑,或者简单处理了。)
#include<iostream> using namespace std; #define Max_Data 100//转发表数据项数量 struct Data//数据项结构 { char Add;//地址 int port;//端口 }; struct SendTable//转发表结构 { Data data[Max_Data]; int write;//写指针,指向下一个要写的位置 }sendTable; void initSendTable() { for(int i=0;i<Max_Data;i++) { sendTable.data[i].Add='0'; sendTable.data[i].port=0; } sendTable.write=0; } int index;//记录匹配项 bool Find(Data data)//查找转发表,若找到返回ture,找不到返回false { for(int i=0;i<Max_Data;i++) { if(sendTable.data[i].Add==data.Add) { index=i; return true; } } return false; } void AddSendTable(Data data)//向转发表当前指针处添加数据项,若转发表满则循环覆盖 { sendTable.data[sendTable.write].Add=data.Add; sendTable.data[sendTable.write].port=data.port; sendTable.write=(sendTable.write+1)%Max_Data; } void OutSendTable() { cout<<"********SendTable********"<<"\n"; for(int i=0;i<sendTable.write;i++)//注意:要是写满在轮转回来的话这种方法就不行了。 { cout<<sendTable.data[i].Add<<" "<<sendTable.data[i].port<<"\n"; } cout<<"*************************"<<"\n"; } void main() { Data sourceData,destinationData; char source,destination; int port; initSendTable();//初始化转发表 while(true) { cout<<"Input Source Address and Prot:\n"; cin>>source>>port; sourceData.Add=source; sourceData.port=port; cout<<"Input destination Address:\n"; cin>>destination; destinationData.Add=destination; destinationData.port=0;//由于目的地址不需要输入端口号,此处将其置0 if(!Find(sourceData))//查找转发表,若找不到则将源地址添加如转发表 AddSendTable(sourceData); if(!Find(destinationData))//查找转发表,若找不到则将此帧从所有其他端口发送给别的网桥 cout<<"Send this Data to other bridge through other port\n"; else { if(sendTable.data[index].port==sourceData.port)//若收到此帧的端口和目的地址再转发表存储的端口相同,说明源地址和目的地址处在同一网段内,目的主机已经收到此帧,须将其丢弃 cout<<"This Data already received,so give it up.\n"; else//若端口不同,则通过查找到的端口将此帧发出 cout<<"Send this Data through port "<<sendTable.data[index].port<<"\n"; } OutSendTable();//打印转发表 } }
运行结果: