ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Distance Vector Algorithm in C

Updated on June 22, 2011

Distance Vector Routing

Distance Vector Routing Algorithm in C

In computer communication theory relating to packet-switched networks, a distance-vector routing protocol is one of the two major classes of routing protocols, the other major class being the link-state protocol. A distance-vector routing protocol uses the Bellman-Ford algorithm to calculate paths.

A distance-vector routing protocol requires that a router informs its neighbors of topology changes periodically and, in some cases, when a change is detected in the topology of a network. Compared to link-state protocols, which require a router to inform all the nodes in a network of topology changes, distance-vector routing protocols have less computational complexity and message overhead.

Distance Vector means that Routers are advertised as vector of distance and direction. 'Direction' is represented by next hop address and exit interface, whereas 'Distance' uses metrics such as hop count.

Routers using distance vector protocol do not have knowledge of the entire path to a destination. Instead DV uses two methods:

  1. Direction in which or interface to which a packet should be forwarded.
  2. Distance from its destination.

Examples of distance-vector routing protocols include Routing Information Protocol Version 1 & 2, RIPv1 and RIPv2 and IGRP. EGP and BGP are not pure distance-vector routing protocols because a distance-vector protocol calculates routes based only on link costs whereas in BGP, for example, the local route preference value takes priority over the link cost.

Distance vector algorithm routing implementation in C

#include<stdio.h>

struct node
{
	unsigned dist[20];
	unsigned from[20];
}rt[10];

int main()
{
	int dmat[20][20];
	int n,i,j,k,count=0;
	printf("\nEnter the number of nodes : ");
	scanf("%d",&n);
	printf("\nEnter the cost matrix :\n");
	for(i=0;i<n;i++)
		for(j=0;j<n;j++)
		{	
			scanf("%d",&dmat[i][j]);
			dmat[i][i]=0;
			rt[i].dist[j]=dmat[i][j];
			rt[i].from[j]=j;
		}
		do
		{	
			count=0;
			for(i=0;i<n;i++)
			for(j=0;j<n;j++)
			for(k=0;k<n;k++)
				if(rt[i].dist[j]>dmat[i][k]+rt[k].dist[j])
				{
					rt[i].dist[j]=rt[i].dist[k]+rt[k].dist[j];
					rt[i].from[j]=k;
					count++;
				}
		}while(count!=0);
		for(i=0;i<n;i++)
		{
			printf("\n\nState value for router %d is \n",i+1);
			for(j=0;j<n;j++)
			{
				printf("\t\nnode %d via %d Distance%d",j+1,rt[i].from[j]+1,rt[i].dist[j]);
			}
		}	
	printf("\n\n");
}

Makefile

a.out:distanceVector.c
	gcc -ggdb distanceVector.c
PHONY:clean
clean:
	rm a.out *~

Example output

Enter the number of nodes : 4

Enter the cost matrix :
0 3 5 99
3 0 99 1
5 4 0 2
99 1 2 0


State value for router 1 is
   
node 1 via 1 Distance0   
node 2 via 2 Distance3   
node 3 via 3 Distance5   
node 4 via 2 Distance4

State value for router 2 is
   
node 1 via 1 Distance3   
node 2 via 2 Distance0   
node 3 via 4 Distance3   
node 4 via 4 Distance1

State value for router 3 is
   
node 1 via 1 Distance5   
node 2 via 4 Distance3   
node 3 via 3 Distance0   
node 4 via 4 Distance2

State value for router 4 is
   
node 1 via 2 Distance4   
node 2 via 2 Distance1   
node 3 via 3 Distance2   
node 4 via 4 Distance0

Comments

    0 of 8192 characters used
    Post Comment

    • profile image

      adithya 

      5 years ago

      I need in java can u try it...

    • profile image

      unknown 

      6 years ago

      plz add comments next to code... and elucidate it!

    • profile image

      santhosh.m 

      6 years ago

      it more helpful for all

    • prabhakar gouda profile imageAUTHOR

      prabhakar gouda 

      6 years ago from Bangalore

      @tarun can you please try for the matrix which kishore has mentioned

    • profile image

      Tarun Kumar 

      6 years ago

      I would definitely love to help but first give me a matrix where DV fails to work,

      i want this to push my code to a limit and want to check how efficient it is .

    • prabhakar gouda profile imageAUTHOR

      prabhakar gouda 

      6 years ago from Bangalore

      Hey guy please take tarun help for more efficient code .... Thanks Tarun

    • profile image

      Tarun Kumar 

      6 years ago

      hey guys can you give me a matrix or scenario where distance vector does not work, i am doing project on DV algo and i need to prove that in these kind of cases DV fails to work.

    • profile image

      Quit 

      6 years ago

      @Kishore

      its not for negative costs !

      its only for positive values.

      if you want it for negative costs, then implement it through dijkstra algorithm.

      thanks. :)

    • profile image

      yo baby 

      6 years ago

      thanx

    • profile image

      kishore 

      6 years ago

      could you brief how this works

      thanks!

    • profile image

      kishore 

      6 years ago

      I get an infinite loop on cost matrix

      0 6 2 7

      4 0 4 -1

      8 5 0 2

      7 -1 7 0

      ???

      Help!

    • profile image

      raj 

      6 years ago

      i understood jst nw

    • profile image

      raj 

      6 years ago

      implementation is nice bt starting one is bad

    • profile image

      Sid Vj 

      6 years ago

      I deserve to be winner of big boss. But don't know why Jui is winner. Anyways love you Sunny.

    • profile image

      DjRocky 

      6 years ago

      Wow ............. Idiot's !

    • profile image

      Pradeep 

      7 years ago

      Last post agreed Cost[2][3]is ? then how come the value ofCost[3][2] is 4?????????????

    • profile image

      7 years ago

      Shouldn't the example cost matrix be symmetric? Cost[2][3] is 99 (99 means "infinity" here, I guess) but Cost[3][2] is 4...

    • profile image

      Dan P 

      7 years ago

      are the [20]'s assuming that there won't be more than 20 routers? How would you do that dynamically if you can't guarantee that?

    • prabhakar gouda profile imageAUTHOR

      prabhakar gouda 

      7 years ago from Bangalore

      hey vygi if you know java then you can convert it into java right .... it is not a big deal to convert to c to java

    • prabhakar gouda profile imageAUTHOR

      prabhakar gouda 

      7 years ago from Bangalore

      @haribabu thanks ra

    • profile image

      vygi 

      7 years ago

      i want in java

    • profile image

      haribabu 

      7 years ago

      mastu undi ra bai program.........

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)