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

typedef struct node{
char dstNet[5];
int distance;
char nextSkip[5];
}RTable;

RTable RT1[1000]; RTable RT2[1000]; int l1, l2;
char nearR1[5];

void InitRTable(RTable* RT){
printf("请为当前路由器添加路由表项(目的网络 距离 下一跳路由器):\n");
for(int i = 0; i < 1000; i++){
scanf("%s %d %s", RT[i].dstNet, &RT[i].distance, RT[i].nextSkip);
if(RT[i].distance == 0){
break;
}
}
l1 = i;
}

void AddNearRouter(){
printf("\n请输入相邻路由器名称:\n");
scanf("%s", nearR1);
}

void InitNearRTable(){
printf("\n请为相邻路由器%s添加路由表项(目的网络 距离 下一跳路由器):\n", nearR1);
for(int i = 0; i < 1000; i++){
scanf("%s %d %s", RT2[i].dstNet, &RT2[i].distance, RT2[i].nextSkip);
if(RT2[i].distance == 0){
break;
}
}
l2 = i;
}

void UpdateNearRTable(RTable* RT2, char* nearR){ for(int p = 0; p < l2; p++){ RT2[p].distance = RT2[p].distance + 1; strcpy(RT2[p].nextSkip, nearR); } }

void UpdateRTable(RTable* RT1, RTable* RT2){
for(int p = 0; p < l2; p++){ int finded = 0;
for(int q = 0; q < l1; q++){
if(strcmp(RT2[p].dstNet, RT1[q].dstNet) == 0){ finded = 1;
if(strcmp(RT1[q].nextSkip, RT2[q].nextSkip) == 0){ RT1[q].distance = RT2[p].distance;
}
else{ if(RT2[p].distance + 1 < RT1[q].distance){
RT1[q].distance = RT2[p].distance;
strcpy(RT1[q].nextSkip, RT2[q].nextSkip);
}
}
}
}
if(!finded){ strcpy(RT1[l1].dstNet, RT2[p].dstNet);
RT1[l1].distance = RT2[p].distance;
strcpy(RT1[l1].nextSkip, RT2[p].nextSkip);
l1++;
}
}
}

void PrintRTable(RTable* RT, int len){
printf(" 目的网络 距离 下一跳路由器\n");
for(int i = 0; i < len; i++){
printf(" %s %d %s\n", RT[i].dstNet, RT[i].distance, RT[i].nextSkip);
}
printf("-------------------------------------\n");
}

void Print_Update(){
UpdateRTable(RT1, RT2);
printf("\n-------当前路由器更新后的路由表------\n");
PrintRTable(RT1, l1);
}

int main(){
printf("\n-----------距离向量算法的过程模拟------------\n\n");
InitRTable(RT1);
while(1){ printf("\n-----------是否有新的路由信息(0为否,1为是)------------\n\n"); int choose;
scanf("%d", &choose);
if(choose == 1){ AddNearRouter();
InitNearRTable();
printf("\n----------当前路由器的路由表---------\n");
PrintRTable(RT1, l1);
printf("\n----------相邻路由器的路由表---------\n");
PrintRTable(RT2, l2);
printf("\n-------修改后的路由信息------\n"); UpdateNearRTable(RT2, nearR1); PrintRTable(RT2, l2);
Print_Update();
} else if(choose == 0){ break; }
} printf("\n-----------更新完毕------------\n\n");

优化下列代码使其有更直观更友好的程序界面#include stdioh#include stdlibh#include stringh run this program using the console pauser or add your own getch systempause or input loop 定义路由表结构RTable typedef struct node

原文地址: http://www.cveoy.top/t/topic/fmkd 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录