天天看點

我的C/C++之路-005課(模拟路由表的路由選擇功能)

#include<stdio.h>
#include<stdlib.h>

/*
模拟路由表的路由選擇功能:預先設定路由表,當有一個資料包到來的時候,
檢視其目的位址,用該位址與路由表每項的子網路遮罩相與,若得到的位址與該項位址一緻,
則把該資料包從有這個位址的端口轉發出去(本例子隻适合靜态路由,當然沒動态路由那麼複雜)
*/

//由于路由表長度未知(由路由器管理者添加),不能使用數組了,這裡使用連結清單吧,如果不會,也可以使用數組模拟
typedef struct RouteNode
{
	int ip[4];//ip
	int subnetMask[4];//子網路遮罩
	int port;//資料包送出的接口号,這裡簡單的使用INT類型(實際情況不是這樣的)
	struct RouteNode * next;//下一項路由記錄

}RouterTableList;

void routerTableArithmetic();
void inputRouterTable(RouterTableList *&rtl);
void addRouteNode(RouterTableList *&rtl,int ip[],int subnetMask[],int port);
void displayRouterTable(RouterTableList *rtl);
int findPort(RouterTableList *rtl,int dist_ip[]);
//資料包轉發決策函數
void routerTableArithmetic()
{
	int dist_ip[4] = {192,168,2,110};//資料包目的位址
	
	RouterTableList * rtl;
	inputRouterTable(rtl);
	printf("********** print route table **************\n");
	displayRouterTable(rtl);
	int port = findPort(rtl,dist_ip);
	if(port==-1) printf("***** 沒有找到記錄,不找到從哪裡轉發出去 ******\n");
	else
	printf("********** 資料包将從路由器的端口 %d 轉發出去**************\n",port);
}
//輸入路由表
void inputRouterTable(RouterTableList *&rtl)
{
	rtl = (RouterTableList *)malloc(sizeof(RouterTableList));//頭結點配置設定空間
	rtl->next = NULL;
	//加入路由條目,這裡加3條,大家可以自己設計下,弄個函數什麼的
	int ip[4] = {192,168,1,0};//輸入的是一個網段,不是具體IP,路由配置也是這樣的
	int subnetMask[] = {255,255,255,0};
	addRouteNode(rtl,ip,subnetMask,1);
	int ip2[4] = {192,168,2,0};
	addRouteNode(rtl,ip2,subnetMask,2);
	int ip3[4] = {192,168,3,0};
	addRouteNode(rtl,ip3,subnetMask,3);	
}
//路由節點
void addRouteNode(RouterTableList *&rtl,int ip[],int subnetMask[],int port)
{
	RouterTableList * node,*find;//find是為了儲存連結清單最後一個節點
	node = (RouterTableList *)malloc(sizeof(RouterTableList));//配置設定空間
	for(int i=0;i<4;i++)
	{
		node->ip[i] = ip[i];
	}
	for(i=0;i<4;i++)
	{
		node->subnetMask[i] = subnetMask[i];
	}
	node->port = port;
	node->next = NULL;
	
	find = rtl;
	while(find->next !=NULL)
	{
		find = find->next;
	}
	find->next = node;
}
//查找從哪個端口輸出資料包
int findPort(RouterTableList *rtl,int dist_ip[])
{
	RouterTableList * node = rtl->next;
	int i;
	while(node!=NULL)
	{
		for(i=0;i<4;i++)
			if((dist_ip[i]&node->subnetMask[i])!=node->ip[i]) break;

		if(i>=4) return node->port;
		node = node->next;
	}
	return -1;//-1為找不到記錄
}
//輸出路由表
void displayRouterTable(RouterTableList *rtl)
{
	RouterTableList * node = rtl->next;
	while(node!=NULL)
	{
		printf("IP: %d.%d.%d.%d   subnetMask: %d.%d.%d.%d   port: %d \n",node->ip[0],node->ip[1],node->ip[2],node->ip[3], \
			node->subnetMask[0],node->subnetMask[1],node->subnetMask[2],node->subnetMask[3],node->port);
		node = node->next;
	}
}
           

花了三個小時,挺悲劇的,不過最後還是做了想要的功能--模拟路由表的路由選擇功能

功能簡單,用了後面的一些知識(以前學過,就直接用了,不懂的朋友可以不用看),還是老話:不懂請留言,大牛繞路走