Distance Vector Routing Protocol Program in C
Published: 2024-07-01 09:54:47

## Introduction
The Distance Vector Routing Protocol (DVRP) is a fundamental protocol used in network communications to determine the best path for data packets to traverse a network. It relies on the Bellman-Ford algorithm to compute the shortest paths from a source node to all other nodes in the network. This article provides a comprehensive guide on implementing a Distance Vector Routing Protocol program in C, covering essential concepts, data structures, algorithms, and a detailed code example.


![Distance Vector Routing Protocol Program in C
](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l0as1dmk0gv0q5tki5i5.gif)

## Key Concepts
Before delving into the implementation, it’s crucial to understand the foundational concepts of [Distance Vector Routing Protocol](https://www.tutorialandexample.com/distance-vector-routing-protocol-program-in-c) (DVRP):

**- Distance Vector:**
Each router maintains a table (vector) that contains the distance (cost) to every possible destination in the network.

**- Periodic Updates:**
Routers periodically share their distance vectors with their immediate neighbors.

**- Bellman-Ford Algorithm:**
This algorithm is the core of DVRP, calculating the shortest paths from a source node to all other nodes in the network.

**- Convergence:**
The network reaches convergence when all routers have consistent and accurate routing tables, and no more updates are necessary.

## Data Structures

In C, we can represent the network and routing tables using arrays and structures. Below are the primary data structures used in our DVRP implementation:

**1. Node Structure:**

`typedef struct {
    int id;                  // Node ID
    int distance[MAX_NODES]; // Distance vector to other nodes
    int nextHop[MAX_NODES];  // Next hop to reach each node
} Node;`

**2. Network Representation:**

`define MAX_NODES 10       
Node nodes[MAX_NODES];     // Array of nodes
int costMatrix[MAX_NODES][MAX_NODES]; // Cost matrix representing the network;`


## Algorithm
The DVRP algorithm can be broken down into the following steps:

**Initialization:** Initialize the distance vectors and next hops for all nodes.

**Update Distance Vectors:** Periodically update the distance vectors based on information received from neighbors.

**Bellman-Ford Update:** Apply the Bellman-Ford algorithm to update the routing tables.

**Convergence Check:** Check if the network has reached convergence.

## Implementation

Here is a detailed implementation of the Distance Vector Routing Protocol in C:
typedef struct {
    int id;
    int distance[MAX_NODES];
    int nextHop[MAX_NODES];
} Node;

Node nodes[MAX_NODES];
int costMatrix[MAX_NODES][MAX_NODES];
int numNodes;

void initializeNodes() {
    for (int i = 0; i < numNodes; i++) {
        for (int j = 0; j < numNodes; j++) {
            if (i == j) {
                nodes[i].distance[j] = 0;
                nodes[i].nextHop[j] = i;
            } else if (costMatrix[i][j] != 0) {
                nodes[i].distance[j] = costMatrix[i][j];
                nodes[i].nextHop[j] = j;
            } else {
                nodes[i].distance[j] = INFINITY;
                nodes[i].nextHop[j] = -1;
            }
        }
    }
}

void updateDistanceVector(int node) {
    for (int i = 0; i < numNodes; i++) {
        if (i != node) {
            for (int j = 0; j < numNodes; j++) {
                if (nodes[node].distance[j] > costMatrix[node][i] + nodes[i].distance[j]) {
                    nodes[node].distance[j] = costMatrix[node][i] + nodes[i].distance[j];
                    nodes[node].nextHop[j] = i;
                }
            }
        }
    }
}

void printRoutingTable() {
    for (int i = 0; i < numNodes; i++) {
        printf("Routing table for node %d:\n", i);
        printf("Destination\tDistance\tNext Hop\n");
        for (int j = 0; j < numNodes; j++) {
            if (nodes[i].distance[j] == INFINITY) {
                printf("%d\t\tINFINITY\t-\n", j);
            } else {
                printf("%d\t\t%d\t\t%d\n", j, nodes[i].distance[j], nodes[i].nextHop[j]);
            }
        }
        printf("\n");
    }
}

int main() {
    printf("Enter the number of nodes: ");
    scanf("%d", &numNodes);`

    `printf("Enter the cost matrix:\n");
    for (int i = 0; i < numNodes; i++) {
        for (int j = 0; j < numNodes; j++) {
            scanf("%d", &costMatrix[i][j]);
        }
    }

    initializeNodes();

    int converged = 0;
    while (!converged) {
        converged = 1;
        for (int i = 0; i < numNodes; i++) {
            int oldDistance[MAX_NODES];
            for (int j = 0; j < numNodes; j++) {
                oldDistance[j] = nodes[i].distance[j];
            }
            updateDistanceVector(i);
            for (int j = 0; j < numNodes; j++) {
                if (nodes[i].distance[j] != oldDistance[j]) {
                    converged = 0;
                }
            }
        }
    }

    printRoutingTable();

    return 0;
}`

### Detailed Explanation

**- Initialization:**

The initializeNodes() function initializes the distance vectors and next hops for all nodes based on the provided cost matrix. Each node initially knows the direct costs to its neighbors and assumes infinite cost for non-neighboring nodes.

**- Update Distance Vectors:**

The updateDistanceVector(int node) function updates the distance vector of the specified node using the Bellman-Ford algorithm. It iterates through all nodes, updating the distance and next hop for each destination if a shorter path is found via a neighboring node.

**- Convergence Check:**

The main loop continues to update distance vectors until the network reaches convergence. Convergence is achieved when no node's distance vector changes during an iteration, indicating that all nodes have consistent and accurate routing information.

**- Print Routing Table:**

The printRoutingTable() function prints the routing tables for all nodes, showing the distance to each destination and the next hop. This allows for easy verification of the protocol's correctness and effectiveness.

## Conclusion
Implementing the Distance Vector Routing Protocol in C offers practical insights into network routing concepts and the Bellman-Ford algorithm. This basic implementation serves as a foundation for further enhancements, such as handling link failures, supporting larger networks, and optimizing performance. By experimenting with this code, one can gain a deeper understanding of dynamic routing protocols and their real-world applications.