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

//定义路由表结构RTable
typedef struct node{
char dstNet[5];
int distance;
char nextSkip[5];
} RTable;

RTable RT1[1000]; //当前路由器路由表
RTable RT2[1000]; //相邻路由器的路由表
int l1, l2; //记录RT1[]和RT2[]的长度
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) {
l1 = i; //记录RT1[]的长度
break;
}
}
}

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) {
l2 = i; //记录RT2[]的长度
break;
}
}
}

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); printf("\n-------更新后的路由表------\n"); Print_Update();
}
else if (choose == 0) { printf("\n-----------更新完毕------------\n\n"); break; } }

优化下列代码使其有更友好的程序界面#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 ch

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

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