简单路由器设计与实现.doc

上传人:rrsccc 文档编号:9006489 上传时间:2021-01-29 格式:DOC 页数:38 大小:1.40MB
返回 下载 相关 举报
简单路由器设计与实现.doc_第1页
第1页 / 共38页
简单路由器设计与实现.doc_第2页
第2页 / 共38页
简单路由器设计与实现.doc_第3页
第3页 / 共38页
简单路由器设计与实现.doc_第4页
第4页 / 共38页
简单路由器设计与实现.doc_第5页
第5页 / 共38页
点击查看更多>>
资源描述

《简单路由器设计与实现.doc》由会员分享,可在线阅读,更多相关《简单路由器设计与实现.doc(38页珍藏版)》请在三一文库上搜索。

1、简单路由器设计与实现(选做)1.实验目的熟悉并掌握路由器的工作原理;熟悉Winpcap编程,掌握数据包捕获与发送的方法;在理解IP协议、ICMP协议与路由基本工作原理的基础上,完成一个(软件)路由器基本功能的设计与编程实现。2.实验环境 接入局域网的PC机; 操作系统:Windows xp, Windows 7等; 推荐开发工具:Visual Studio 2010; 推荐编程语言:C+/ Visual C+; 函数库/开发包:Winpcap。3.实验内容(1) 学习并掌握winpcap编程:自行完成WinPcap教程中的内容,从而掌握winpcap编程。内容包括但不限于:a) 获取设备列表;

2、b) 打开一个适配器并抓包(分组);c) 解析分组;d) 发送分组;学习内容及源程序参见WinPcap官方教程:http:/www.winpcap.org/docs/docs_412/html/group_wpcap_tut.html。(2) 利用winpcap开发包实现简单路由程序,该路由程序应该至少包括以下功能:a) IP数据包捕获和转发;b) ARP请求与解析;c) 重新计算IP数据包的头部校验和;d) 处理IP数据包的头部校验和;处理IP数据包的TTL值;e) 静态路由表维护。在下图所示的完了过拓扑结构中,当所开发的路由器程序部署并运行在计算机C上时,它将(作为一个路由器)能够连通两个

3、子网,正确地捕获、转发来自计算机A和计算机B的分组,使得两个子网中的主机能够互相访问图5-1 实验验证环境配置示意图4.实验方式每位同学独立上机编程实验,实验指导教师现场指导。5.参考内容(1) WinPcap简介Winpcap (windows packet capture)是windows平台下一个免费、公共的网络访问系统。开发Winpcap项目的目的在于为win32应用程序提供访问网络底层的能力。它用于windows系统下的直接的网络编程。关于Winpcap的介绍请参阅http:/ Winpcap主要函数及功能介绍Winpcap部分主要函数及其功能介绍如下:(1).int pcap_fi

4、ndalldevs_ex(char * source, struct pcap_rmtauth * auth, pcap_if_t * alldevs, char * errbuf)函数功能:Create a list of network devices that can be opened withpcap_open().参数说明:source:a char* buffer that keeps the source localtion, according to the new WinPcap syntax. This source will be examined looking fo

5、r adapters (local or remote) or pcap files,The strings that must be prepended to the source in order to define if we want local/remote adapters or files is defined in the new Source Specification Syntax .auth:a pointer to a pcap_rmtauth structure. This pointer keeps the information required to authe

6、nticate the RPCAP connection to the remote host. This parameter is not meaningful in case of a query to the local host: in that case it can be NULL.alldevs:a struct pcap_if_t pointer, which will be properly allocated inside this function. When the function returns, it is set to point to the first el

7、ement of the interface list; each element of the list is of type struct pcap_if_t.errbuf: a pointer to a user-allocated buffer (of size PCAP_ERRBUF_SIZE) that will contain the error message (in case there is one).返回值:0 if everything is fine, -1 if some errors occurred. The list of the devices is ret

8、urned in the alldevs variable. When the function returns correctly, alldevs cannot be NULL. In other words, this function returns -1 also in case the system does not have any interface to list.(2).void pcap_freealldevs_ex(pcap_if_t * alldevsp)函数功能:Free an interface list returned by pcap_findalldevs(

9、).(3).pcap_t* pcap_open(const char * source, int snaplen, int flags, int read_timeout, struct pcap_rmtauth * auth, char * errbuf)函数功能:Open a generic source in order to capture / send (WinPcap only) traffic.参数说明:source:zero-terminated string containing the source name to open. The source name has to

10、include the format prefix according to the new Source Specification Syntax and it cannot be NULL.On on Linux systems with 2.2 or later kernels, a device argument of any can be used to capture packets from all interfaces. In order to makes the source syntax easier, please remember that:the adapters r

11、eturned by the pcap_findalldevs_ex() can be used immediately by the pcap_open()in case the user wants to pass its own source string to the pcap_open(), the pcap_createsrcstr() helps in creating the correct source identifier.snaplen:length of the packet that has to be retained. For each packet receiv

12、ed by the filter, only the first snaplen bytes are stored in the buffer and passed to the user application. For instance, snaplen equal to 100 means that only the first 100 bytes of each packet are stored.flags:keeps several flags that can be needed for capturing packets. The allowed flags are defin

13、ed in the pcap_open() flags .read_timeout:read timeout in milliseconds. The read timeout is used to arrange that the read not necessarily return immediately when a packet is seen, but that it waits for some amount of time to allow more packets to arrive and to read multiple packets from the OS kerne

14、l in one operation. Not all platforms support a read timeout; on platforms that dont, the read timeout is ignored.auth:a pointer to a struct pcap_rmtauth that keeps the information required to authenticate the user on a remote machine. In case this is not a remote capture, this pointer can be set to

15、 NULL.errbuf:a pointer to a user-allocated buffer which will contain the error in case this function fails. The pcap_open() and findalldevs() are the only two functions which have this parameter, since they do not have (yet) a pointer to a pcap_t structure, which reserves space for the error string.

16、 Since these functions do not have (yet) a pcap_t pointer (the pcap_t pointer is NULL in case of errors), they need an explicit errbuf variable. errbuf may also be set to warning text when pcap_open_live() succeds; to detect this case the caller should store a zero-length string in errbuf before cal

17、ling pcap_open_live() and display the warning to the user if errbuf is no longer a zero-length string.返回值: A pointer to a pcap_t which can be used as a parameter to the following calls (pcap_compile()and so on) and that specifies an opened WinPcap session. In case of problems, it returns NULL and th

18、e errbuf variable keeps the error message.(4). int pcap_next_ex(pcap_t * p, struct pcap_pkthdr * pkt_header, const u_char * pkt_data)函数功能:Read a packet from an interface or from an offline capture.This function is used to retrieve the next available packet, bypassing the callback method traditionall

19、y provided by libpcap. pcap_next_ex fills the pkt_header and pkt_data parameters (see pcap_handler() with the pointers to the header and to the data of the next captured packet.返回值:The return value can be:1 if the packet has been read without problems0 if the timeout set with pcap_open_live() has el

20、apsed. In this case pkt_header and pkt_data dont point to a valid packet-1 if an error occurred-2 if EOF was reached reading from an offline capture(5). int pcap_compile(pcap_t * p, struct bpf_program * fp, char * str, int optimize, bpf_u_int32 netmask)函数功能:Compile a packet filter, converting an hig

21、h level filtering expression (see Filtering expression syntax) in a program that can be interpreted by the kernel-level filtering engine.(6). int pcap_setfilter(pcap_t * p, struct bpf_program * fp)函数功能:Associate a filter to a capture. 此函数是要和函数pcap_compile()配合使用。(7). int pcap_sendpacket(pcap_t * p, u

22、_char * buf, int size)函数功能: Send a raw packet.6.实验步骤6.1 WinPcap开发包安装与配置下载、安装WinPcap开发包,配置VisualStudio 2010开发环境。具体步骤请同学们参阅网上资料自行完成。6.2 用户界面设计(1).首先打开vs2010,新建工程,选择MFC Application,输入工程名,点击OK,图5-2点击next,选择Dialog based,点击Next跳到最后一个页面选择.Dlg,点击finish。图5-3图5-4到此为止工程新建完毕,运行会出现以下页面,下面就为这个对话框拖拽控件。图5-5首先将对话框上面

23、的三个控件删除,并拖拽相应的控件得到如下效果:图5-6图5-7其中对话框可在Resource View打开,控件在Toolbox中可以找到,图5-8其中启动、退出、添加路由、删除路由为button控件,两个空白区为List Box,日志、路由表、子网掩码、目的地址、下一跳步为Static Text,三个输入IP的控件为IP Address Control,将控件拖拽到相应的位置并且在控件的属性框中修改控件的Caption以及ID。启动ONSTART_BUTTON退出ONSTOP_BUTTON日志IDC_STATIC第一个空白区LOGGER_LIST路由表IDC_STATIC第二个空白区ROUT

24、ER_LIST子网掩码IDC_STATIC子网掩码对应的IP输入区IDC_NETMASK目的地址IDC_STATIC目的地址对应的IP输入区IDC_IPADDRESS下一跳步IDC_STATIC下一跳步对应的IP输入区IDC_NEXTHOP添加路由ADD_ROUTER_BUTTON删除路由DELETE_ROUTER_BUTTON6.3 代码实现(1). 事件响应函数及主流程控件添加完成后为Button添加相应的单击事件并修改单击事件名称,对应关系如下:启动OnStartClickedButton()退出OnBnClickedButton()添加路由OnAddRouterButton()删除路由

25、OnDeleteRouterButton()VC程序首先执行程序初始化函数OnInitDialog(),在此函数中我们获取了MFC窗体指针。当我们点击“启动”按钮时,程序会执行OnStartClickedButton()函数,此函数流程图如下图所示:图5-9当我们点击结束按钮时程序会执行OnBnClickedButton(),程序自动退出。当程序退出时会触发ON_WM_DESTROY()消息,从而会执行OnDestroy()函数,并且程序在执行过程中每隔一段时间会执行OnTimer()函数。(2). 主要数据结构和函数声明首先将程序所用变量以及函数复制到VCRouterDlg.cpp文件中:#

26、defineMAX_IF5 / 最大接口数目#pragma pack(1)typedef struct FrameHeader_t / 帧首部 UCHARDesMAC6; / 目的地址 UCHARSrcMAC6; / 源地址 USHORTFrameType; / 帧类型 FrameHeader_t;typedef struct ARPFrame_t / ARP帧FrameHeader_tFrameHeader; / 帧首部 WORDHardwareType; / 硬件类型WORDProtocolType; / 协议类型BYTEHLen; / 硬件地址长度BYTEPLen; / 协议地址长度WO

27、RDOperation; / 操作值UCHARSendHa6; / 源MAC地址ULONGSendIP; / 源IP地址UCHARRecvHa6; / 目的MAC地址ULONGRecvIP; / 目的IP地址 ARPFrame_t;typedef struct IPHeader_t / IP首部BYTEVer_HLen; / 版本+头部长度BYTETOS; / 服务类型WORDTotalLen; / 总长度WORDID; / 标识WORDFlag_Segment; / 标志+片偏移BYTETTL; / 生存时间BYTEProtocol; / 协议WORDChecksum; / 头部校验和ULO

28、NGSrcIP; / 源IP地址ULONGDstIP; / 目的IP地址 IPHeader_t;typedef struct ICMPHeader_t / ICMP首部BYTE Type; / 类型BYTE Code; / 代码WORD Checksum; / 校验和WORD Id; / 标识WORD Sequence; / 序列号 ICMPHeader_t;typedef struct IPFrame_t / IP帧FrameHeader_tFrameHeader; / 帧首部IPHeader_tIPHeader; / IP首部 IPFrame_t;typedef struct ip_t /

29、 网络地址ULONGIPAddr; / IP地址ULONGIPMask; / 子网掩码 ip_t;typedef struct IfInfo_t / 接口信息CStringDeviceName; / 设备名CStringDescription; / 设备描述UCHARMACAddr6; / MAC地址CArray ip; / IP地址列表pcap_t*adhandle; / pcap句柄 IfInfo_t;typedef struct SendPacket_t / 发送数据包结构intlen; / 长度BYTEPktData2000;/ 数据缓存ULONGTargetIP; / 目的IP地址U

30、INT_PTRn_mTimer; / 定时器UINTIfNo; / 接口序号 SendPacket_t;typedef struct RouteTable_t / 路由表结构ULONGMask; / 子网掩码ULONGDstIP; / 目的地址ULONGNextHop; / 下一跳步UINTIfNo; / 接口序号 RouteTable_t;typedef struct IP_MAC_t / IP-MAC地址映射结构ULONGIPAddr; / IP地址UCHARMACAddr6; / MAC地址 IP_MAC_t;/ 全局变量/*/IfInfo_tIfInfoMAX_IF; / 接口信息数组

31、intIfCount; / 接口个数UINT_PTR TimerCount; / 定时器个数CList SP; / 发送数据包缓存队列CList IP_MAC; / IP-MAC地址映射列表CList RouteTable; / 路由表CMyRouterDlg *pDlg ; / 对话框指针CMutex mMutex(0,0,0); / 互斥/*/ 全局函数/*/ IP地址转换CString IPntoa(ULONG nIPAddr);/ MAC地址转换CString MACntoa(UCHAR *nMACAddr);/ MAC地址比较bool cmpMAC(UCHAR *MAC1, UCHA

32、R *MAC2);/ MAC地址复制void cpyMAC(UCHAR *MAC1, UCHAR *MAC2);/ MAC地址设置void setMAC(UCHAR *MAC, UCHAR ch);/ IP地址查询bool IPLookup(ULONG ipaddr, UCHAR *p);/ 数据包捕获线程UINT Capture(PVOID pParam);/ 获取本地接口MAC地址线程UINT CaptureLocalARP(PVOID pParam);/ 发送ARP请求void ARPRequest(pcap_t *adhandle, UCHAR *srcMAC, ULONG srcIP

33、, ULONG targetIP);/ 查询路由表DWORD RouteLookup(UINT &ifNO, DWORD desIP, CList *routeTable);/ 处理ARP数据包void ARPPacketProc(struct pcap_pkthdr *header, const u_char *pkt_data);/ 处理IP数据包void IPPacketProc(IfInfo_t *pIfInfo, struct pcap_pkthdr *header, const u_char *pkt_data);/ 处理ICMP数据包void ICMPPacketProc(IfI

34、nfo_t *pIfInfo, BYTE type, BYTE code, const u_char *pkt_data);/ 检查IP数据包头部校验和是否正确int IsChecksumRight(char * buffer);/ 计算校验和unsigned short ChecksumCompute(unsigned short *buffer, int size);(3). 函数代码实现/ 获取本地接口MAC地址线程UINT CaptureLocalARP(PVOID pParam)intres;struct pcap_pkthdr*header;const u_char*pkt_dat

35、a;IfInfo_t*pIfInfo;ARPFrame_t*ARPFrame;CStringDisplayStr;pIfInfo = (IfInfo_t *)pParam;while (true)Sleep(50);res = pcap_next_ex( pIfInfo-adhandle , &header, &pkt_data);/ 超时 if (res = 0) continue; if (res 0)ARPFrame = (ARPFrame_t *) (pkt_data);/ 得到本接口的MAC地址if (ARPFrame-FrameHeader.FrameType = htons(0x

36、0806) & (ARPFrame-Operation = htons(0x0002) & (ARPFrame-SendIP = pIfInfo-ip0.IPAddr) cpyMAC(pIfInfo-MACAddr, ARPFrame-SendHa);return 0;void setMAC(UCHAR *MAC, UCHAR ch)for (int i=0; i6; i+) MACi = ch;return;/ 发送ARP请求void ARPRequest(pcap_t *adhandle, UCHAR *srcMAC, ULONG srcIP, ULONG targetIP)ARPFram

37、e_tARPFrame;inti;for (i=0; i6; i+)ARPFrame.FrameHeader.DesMACi = 255;ARPFrame.FrameHeader.SrcMACi = srcMACi;ARPFrame.SendHai = srcMACi;ARPFrame.RecvHai = 0;ARPFrame.FrameHeader.FrameType = htons(0x0806);ARPFrame.HardwareType = htons(0x0001);ARPFrame.ProtocolType = htons(0x0800);ARPFrame.HLen = 6;ARP

38、Frame.PLen = 4;ARPFrame.Operation = htons(0x0001);ARPFrame.SendIP = srcIP;ARPFrame.RecvIP = targetIP; pcap_sendpacket(adhandle, (u_char *) &ARPFrame, sizeof(ARPFrame_t);void cpyMAC(UCHAR *MAC1, UCHAR *MAC2)for (int i=0; i6; i+) MAC1i=MAC2i;/ 比较两个MAC地址是否相同bool cmpMAC(UCHAR *MAC1, UCHAR *MAC2)for (int i=0; iadhandle, &header, &pkt_data); if (res = 1)FrameHeader_t*fh;fh = (FrameHeader_t *) pkt_data;switch (ntohs(fh-FrameType)case 0x0806:ARPFrame_t *ARPf;ARPf = (ARPFrame_t *)pkt_data;/TRACE1(收到ARP包 源IP为:%d

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 社会民生


经营许可证编号:宁ICP备18001539号-1