Implement distance vector routing algorithm for obtaining routing tables at each node.
Implement Distance vector routing algorithm
Input Graph:
Source Code:
File Name: distance_vector_routing.c
#include<stdio.h>
// Structure to represent the routing table of each router
struct RoutingTable {
unsigned distance[20]; // Distance to each destination node
unsigned nextHop[20]; // Next hop to reach each destination node
} rt[10];
int main() {
int costMatrix[20][20]; // Cost matrix input by user
int numNodes; // Number of routers/nodes in the network
int i, j, k; // Loop counters
int updated; // Flag to check if any update is made in the routing table
// Read the number of routers
printf("\nEnter the number of nodes (routers): ");
scanf("%d", &numNodes);
// Read the cost matrix
printf("\nEnter the cost matrix:\n");
for (i = 0; i < numNodes; i++) {
for (j = 0; j < numNodes; j++) {
scanf("%d", &costMatrix[i][j]);
// Distance from a node to itself is 0
if (i == j) {
costMatrix[i][j] = 0;
}
// Initialize routing table
rt[i].distance[j] = costMatrix[i][j]; // Initial distance
rt[i].nextHop[j] = j; // Initial next hop (direct connection)
}
}
// Apply Distance Vector Routing algorithm (Bellman-Ford logic)
do {
updated = 0; // Assume no updates
for (i = 0; i < numNodes; i++) {
for (j = 0; j < numNodes; j++) {
for (k = 0; k < numNodes; k++) {
// Check if the path from i to j via k is shorter
if (rt[i].distance[j] > costMatrix[i][k] + rt[k].distance[j]) {
rt[i].distance[j] = costMatrix[i][k] + rt[k].distance[j];
rt[i].nextHop[j] = k; // Update next hop
updated = 1; // Mark that an update occurred
}
}
}
}
} while (updated); // Repeat until no updates
// Print final routing tables
for (i = 0; i < numNodes; i++) {
printf("\nRouting Table for Router %d:\n", i + 1);
printf("Destination\tNext Hop\tDistance\n");
for (j = 0; j < numNodes; j++) {
printf(" %d\t\t %d\t\t %d\n", j + 1, rt[i].nextHop[j] + 1, rt[i].distance[j]);
}
}
printf("\n");
return 0;
}
Output:
$ gcc distance_vector_routing.c
$ ./a.out
Enter the number of nodes (routers): 4
Enter the cost matrix:
0 3 5 99
3 0 99 1
5 4 0 2
99 1 2 0
Routing Table for Router 1:
Destination Next Hop Distance
1 1 0
2 2 3
3 3 5
4 2 4
Routing Table for Router 2:
Destination Next Hop Distance
1 1 3
2 2 0
3 4 3
4 4 1
Routing Table for Router 3:
Destination Next Hop Distance
1 1 5
2 4 3
3 3 0
4 4 2
Routing Table for Router 4:
Destination Next Hop Distance
1 2 4
2 2 1
3 3 2
4 4 0
๐ป Run This C Program
Implement distance vector routing algorithm for obtaining routing tables at each node.
The selected C program is loaded
automatically into the editor.
Edit the program, provide input through
STDIN if required
and click Run.
The compiler is embedded using OneCompiler.
Your C program runs inside the embedded
C environment; Study Glance does not execute
C code directly on your web server.
Enter the input values of the program in the
STDIN box before clicking Run.