Sei sulla pagina 1di 28

P.E.S.

INSTITUTE OF TECHNOLOGY, Bangalore – 560 085


Session: Aug - Dec 2009

CCN LABORATORY MANUAL

VII SEMESTER TELECOMMUNICATION ENGG

CONTENTS

CCN Programming using C/C++ (3 Lab Sessions)

1. Simulate bit stuffing & de-stuffing using HDLC.

2. Simulate character stuffing & de-stuffing using HDLC

3. a. Encryption of a given message Using Substitution Method.

b. Decryption of a given message Using Substitution Method.


4. a. Encryption of a given message Using Transposition Method.
b. Decryption of a given message Using Transposition Method.
5. Compute Polynomial Code Checksum for CRC-CCITT

6. Simulate the Shortest Path Algorithm


7. Find Minimum Spanning Tree of a Subnet

CCN Experiments using Hardware (1 Lab Session)

8. Asynchronous and Synchronous Communication using RS232 / Optical

Fiber / Twisted Pair / RJ45.


CCN Lab Manual

9. Demonstrate the use of fork function to create two processes and


communicate between them.

10. Demonstrate communication between two PCs using socket function.

11.Demonstrate the operations of rlogin and Telnet.

12.Demonstrate the operations of ftp and Mailbox.

Staff-in-Charge: Sushma Rawal

CCN Programming using C/C++

1. Simulate bit stuffing & de-stuffing using HDLC


Digital communication has its advantages of speed, reliability, etc but
with it comes a problem of control signals. In analog communication the
modulation technique used can be used to generate control signals. Like in
FDM 3 frequencies can be used: one frequency for a low, another one for a
High and finally a third frequency for a control signal. But this isn’t possible
in Digital communication. Bit patterns or Bytes can be reserved for control
signals. These control signals cannot be present in normal data. This can be
achieved for ASCII text or if a few bit patterns are used as data. But when
the whole set of bit patterns or ASCII values are used the special control
signals cannot be present in data and if present should not be interpreted as
control signals but be interpreted as data. This is the reason we use Stuffing.
Stuffing is the process of adding redundant information or increasing the
amount of data transmitted in order to accommodate control signals. This
can be done in 2 ways:

Bit Stuffing:
This is used when a bit oriented communication system is used. Let us
consider the control signals of frame start/end. We give them a
representation of 0111 1110. So now if this is present in the data we are
transmitting we change this patter so that it no longer matches the control
signal of frame start/end. Each time we see 5 ones at the transmitter we
append a 0 instantly so that 6 ones can never exist. An argument can be
raised about the fact why should we add the zero after 5 ones if the 6th bit

2/28
CCN Lab Manual

was a 0 and not a one. The reason is simple enough - the receiver cannot
differentiate between that 0 which is a data and a stuffed 0. For example,

01111101 can now be interpreted as 0111 1110 (assuming 0 is a stuffed 0)


0111 1101 (assuming 0 is data)

So once it is settled that every 5 ones has a zero following it irrespective of


the next bit being a 0 or a 1 lets see what the receiver has to do. The receiver
keeps a count of the ones and each time it receives 5 ones it discards the next
bit if it is a 0 bit which is the stuffed 0 bit and knows this isn’t a control
signal but if the bit after 5 ones is also a 1 it knows its a frame end/start.

HDLC Frame
The high level data link control protocol is a bit oriented protocol which
uses bit stuffing for data transparency. HDLC frame is as shown.

The Control field is used for sequence numbers and acknowledgements and
other purposes. The Data field may contain arbitrary information. The
Checksum field is a minor variation of the CRC code using CRC-CCITT as
the generator. Frames are delimited by 0111 1110 and this sequence is not
allowed in the data field.

Algorithm for Bit Stuffing


1. Input data sequence
2. Add start of frame to output sequence
3. For every bit in input
a. Append bit to output sequence
b. Is bit a 1?
Yes:
Increment count
If count is 5, append 0 to output sequence and reset count
No:
Set count to 0
4. Add stop of frame bits to output sequence

Algorithm for Bit Destuffing:


3/28
CCN Lab Manual

1. Input the stuffed sequence.


2. Remove start of frame from sequence.
3. For every bit in input,
a. Append bit to output sequence.
b. Is bit a 1?
Yes: Increment count. If count is 5, remove next bit (which is
0) and reset count.
No: Set count to 0.
4. Remove end of frame bits from sequence.

/* Program to simulate bit stuffing where the flag byte is 01111110 */


# include <stdio.h>
# include <conio.h>
void main()
{
/* Array is already initialised to 01111110 which is the flag byte. Hence a
counter 'i'
/* has to point to the eight location in the same array */
char ch, array[50]={"01111110"},recd_array[50];
int counter=0,i=8,j,k;
clrscr();
/* Only the data portion of the frame is inputted */
printf("Enter the original data stream for bit stuffing : \n");
while((ch=getche())!='\r')
{
if (ch=='1')
++counter;
else
counter=0;
array[i++]=ch;
if (counter==5) /* If 5 ones are encountered append a zero */
{
array[i++]='0';
counter=0;
}
}
strcat(array,"01111110"); /* Appending the flag byte at the end of the
stream */
/* i now has the value of the flag byte length + data stream length */
4/28
CCN Lab Manual

printf("\nThe stuffed data stream is : \n");


for (j=0;j<i+8;++j)
printf("%c",array[j]);
/* Destuffing */
counter=0;
printf("\nThe destuffed data stream is : \n");
for (j=8,k=0;j<i+8;++j)
{
if (array[j]=='1')
++counter;
else
counter=0;
recd_array[k++]=array[j];
if (counter==6) /* End if six ones are encountered */
break;
else if (counter==5 && array[j+1]=='0') /* If five ones appear,
delete the
following zero */
{
++j;
counter=0;
}
}
for (j=0;j<=k-strlen("01111110");++j)
printf("%c",recd_array[j]); /* Printing the final destuffed array
*/
getch();
}

Output:
Enter the original data stream for bit stuffing :
011011111111110010
The stuffed data stream is :
011111100110111110111110001001111110
The destuffed data stream is :
011011111111110010

2. Simulate character stuffing & de-stuffing using HDLC


Bit stuffing seems to be a foolproof plan but sometimes the communication
system cannot handle bits but can only manipulate bytes (8 bits). In these
5/28
CCN Lab Manual

cases we assume an ASCII set. The main control signals are ETX (End text),
STX (Start text), and DLE (Data Link Escape). Other control signals are also
present like SOH (start of header), EOT (End of transmission) etc but we
will restrict the discussion to ETX, STX, DLE. The principle remains the
same STX (ASCII 02) denotes a start of data and ETX (ASCII 03) the end of
text. Incase ETX or the byte 03 happens to be present in data it should be
treated as data and not end of text. Similar is the case for STX. To make sure
this happens we use another ASCII value called DLE (ASCII 16). Each time
we see a STX in data we make it DLE STX and an ETX is made into DLE
ETX. SO if we receive a ETX or a STX and the previous ASCII value inst
DLE we know it’s a frame start/end. Consider the case when DLE was the
last data byte. The end of text will now become as data as the receiver will
get DLE ETX. So now even DLE is stuffed. So each time transmitter sees
DLE it makes it DLE DLE.

Algorithm for Character Stuffing


1. Input data sequence
2. Add start of frame to output sequence (DLE STX)
3. For every character in input
a. Append character to output sequence
b. Is character DLE?
Yes:
Add DLE to output sequence
3. Add stop of frame chars to output sequence

Algorithm for Character Destuffing:


1. Input stuffed sequence.
2. Remove start of frame from sequence (DLE STX).
3. For every character in input,
a. Append character to output sequence.
b. Is character DLE?
Yes: Remove next DLE from input sequence.
No: Continue.
4. Remove stop of frame character to output sequence (DLE ETX).

/* Program to demonstrate character stuffing */


# include <stdio.h>
# include <conio.h>
# define DLE 16
6/28
CCN Lab Manual

# define STX 2
# define ETX 3
void main()
{
char ch;
char array[100]={DLE,STX}; /* Initialise the array to have */
int i=2,j; /* the frame delimiter bytes initially */
clrscr();
/* Inputting the data stream alone */
printf("Enter the data stream (Ctrl+B->STX, Ctrl+C->ETX, Ctrl+P-
>DLE) : \n");
while ((ch=getch())!='\r')
{
if (ch==DLE) /* Checking for DLE */
{
array[i++]=DLE;
printf("DLE ");
}
else if (ch==STX) printf("STX ");
else if (ch==ETX) printf("ETX ");
else printf("%c ",ch);
array[i++]=ch;
}
array[i++]=DLE;
array[i++]=ETX;
printf("\nThe stuffed stream is \n");
for (j=0;j<i;++j)
{
if (array[j]==DLE) printf("DLE ");
else if (array[j]==STX) printf("STX ");
else if (array[j]==ETX) printf("ETX ");
else printf("%c ",array[j]);
}
/* Destuffing of character stream */
printf("\nThe destuffed data stream is : \n");
for (j=2;j<i-2;++j)
{
if (array[j]==DLE) /* Checking for DLE */
{ printf("DLE "); ++j; }
else if (array[j]==STX)
7/28
CCN Lab Manual

printf("STX ");
else if (array[j]==ETX)
printf("ETX ");
else
printf("%c ",array[j]);
}
getch();
}

Output:
Enter the data stream (Ctrl+B->STX, Ctrl+C->ETX, Ctrl+P->DLE) :
A DLE B
The stuffed stream is
DLE STX A DLE DLE B DLE ETX
The destuffed data stream is :
A DLE B

8/28
CCN Lab Manual

3a.Encryption of a given message by Substitution Method


In cryptography, the messages to be encrypted; known as plaintext,
are transformed by a function that is parameterized by a key. The output of
the encryption process, known as ciphertext, is then transmitted, often by
messenger or radio. We assume that the enemy or intruder, hears and
accurately copies down the complete ciphertext. However, unlike the
intended recipient, he does not know what the decryption key is and so
cannot decrypt the ciphertext easily. Sometimes the intruder cannot only
listen to the communication channel (passive intruder) but can also record
messages and play them later, inject his own messages, or modify legitimate
messages before they get to the receiver (active intruder). The art of
breaking ciphers is called cryptanalysis. The art of devising ciphers
(cryptography) and breaking them (cryptanalysis) is collectively known as
cryptology. It will often be useful to have a notation for relating plaintext,
ciphertext and keys. We will use C=EK(P) to mean that the encryption of the
plaintext P using key K gives the ciphertext C. Similarly, P=DK(C)
represents decryption of C to get the plaintext again. It then follows that
DK(EK(P)) = P
Fundamental rule of cryptography is that one must assume that the
cryptoanalyst knows the general method of encryption used.
Encryption methods are historically divided into two categories:
substitution ciphers and transposition ciphers.
Encryption Method
Cipher C=Ek(P )
Decryption Method
Encryption key-Ek, Decryption key-Dk, Plaintext-P,
Plaintext P=DK(EK(P))

Substitution Ciphers
In a substitution cipher, each letter or group of letters is replaced by
another letter or group of letters to disguise it. A way to do this is to have
each of the symbols in the plaintext, say the 26 letters for simplicity, map
onto some other letter. For example,
Plaintext: a b c d e f g h i j k l m n o p q r s t u v w x y z
Ciphertext: Q W E R T Y U I O P A S D F G H K L Z X C V B N M
This general system is called a mono-alphabetic substitution, with the key
being the 26-letter string corresponding to the full alphabet. For the key
above, the plaintext attack would be transformed into the ciphertext
QZZQEA.
Algorithm for Encryption by Substitution Method
9/28
CCN Lab Manual

1. Read data to be encoded


2. For every character of data
a. If data is between 'a' and 'z' set encoded data to uppercase character
from key
b. If data is between 'A' and 'Z' set encoded data to lowercase
character from key
c. If data between '0' and'9' set encoded data to digit from key
d. else copy data into encoded data’s array.
3. Print encoded data.

/* Encryption by Substitution method */


/* Program to encrypt given data even numbers sequence is a key on which
you change
data change all small letters to big and vice versa*/
# include<string.h>
# include<ctype.h>
# include<stdio.h>
void main()
{
const char sequence[36]="qwertyuiopasdfghjklzxcvbnm4852630791";
char data[100]; /*input data*/
char encoded[100]; /*encoded data*/
int i,len;
printf("\nEnter data to be encoded:");
gets(data);
len=strlen(data);
for(i=0;i<len;++i)
{
if(data[i]>='a' && data[i]<='z')
/*if small letter subtract from 97 so 'a' becomes 0 and convert
sequence[0] to uppercase for 'a'*/
encoded[i]=toupper(sequence[(data[i]-97)]);
else if(data[i]>='A' && data[i]<='Z')
/*if uppercase letter subtract 65 so that 'A' becomes 0 encoded
data
is seqence['A'-65]*/
encoded[i]=sequence[(data[i]-65)];
else if(data[i]>='0' && data[i]<='9')
/*numbers are present at an offset of 26.. so index sequence on
char-48 + 26... so now '0' will be at 26 or sequence[26]*/
10/28
CCN Lab Manual

encoded[i]=sequence[(data[i]-48)+26];
else encoded[i]=data[i];
/*else send punctuation marks or special chars normally*/
}
encoded[len]='\0';
printf("Encoded string : %s",encoded);
}
Output:
Enter data to be encoded: Hello World!
Encoded string : iTSSG vGKSR!

3b.Decryption of a given message by Substitution Method

Algorithm for Decryption by Substitution Method


1. Read encrypted data
2. For every character of data
a. Scan through key to see if data is present
(i) If present get index of character add it to 'a' if data is
uppercase else 'A' if it is in lowercase else '0' if it is a digit.
(ii) If not present copy data into decoded data’s array.
3. Print decoded data.
/* Decryption by Substitution method */
/* Find the given character in key find the location and add that to 'a' or 'A'
or '0' as per
requirements */
# include<stdio.h>
# include<ctype.h>
# include<string.h>
void main()
{
char sequence[36]="qwertyuiopasdfghjklzxcvbnm4852630791";
char data[100]; /*input data*/
char decoded[100]; /*decoded data*/
int i,j,len,present=0;
printf("\nEnter data:");
gets(data);
len=strlen(data);
for(i=0;i<len;++i) /*for every element of input data*/
{
for(j=0;j<36 && !present;++j) /*compare with sequence*/
11/28
CCN Lab Manual

{
if(sequence[j]==tolower(data[i])) /*if data matches*/
/*numbers are not changed by tolower/toupper*/
{
if(isupper(data[i]))
/*numbers return false for this only upper case letters will
return true*/
decoded[i]='a'+j;
/*an upper case letter is converted to lower case*/
else if(islower(data[i]))
decoded[i]='A'+j;
/*a lower case letter is converted to upper case*/
else /*a digit is encountered*/
decoded[i]='0'+(j-26); /*digits are at an offset of
26*/
present=1; /*set flag saying digit is present*/
}
}
if(!present)
decoded[i]=data[i]; /*assign normal data*/
else present=0; /*is present is 1 make it 0 for next time*/
}
decoded[len]='\0';
printf("\nDecoded string is : %s",decoded);
}

Output:
Enter data: iTSSG vGKSR!
Decoded string is : Hello World!

4a.Encryption of a given message by Transposition Method

Transposition Ciphers
Substitution ciphers preserve the order of the plaintext symbols but
disguise them. Transposition ciphers, in contrast, reorder the letters but do
not disguise them. The figure below depicts a common transposition cipher,
the columnar transposition. The cipher is keyed by a word or phrase not
containing any repeated letters. In this example, MEGABUCK is the key.
The purpose of the key is to number the columns, column 1 being under the
12/28
CCN Lab Manual

letter closet to the start of the alphabet and so on. The plain text is written
horizontally, in rows. The ciphertext is read out by columns, starting with
the
column whose key letter is the lowest.
Plain text :
pleasetransferonemilliondollarstomyswissbankaccountsixtwotwo
MEGABUCK
74512836
pleasetr
ansferon
emillion
dollarst
omyswiss
bankacco
untsixtw
otwoabcd

Ciphertext:
AFLLSKSOSELAWAIATOOSSCTCLNMOMANTESILYNTWRNNT
SOWDPAEDOBUOERIRICXB

Algorithm for Encryption by Transposition Method


1. Get sequence of characters in Cipher i.e. MEGABUCK
2. Get data to be decoded.
3. Arrange data horizontally under MEGABUCK
4. Add '.' to make last row complete
5. For every column of MEGABUCK
a. Find next column to send using sequence
b. Send data under this letter i.e. print the data under this letter
c. Jump back to 5 till all columns aren’t done

/* Encryption by Transposition method */


# include<string.h>
# include<stdio.h>
void main()
{
char data[100];
char wrd[]="MEGABUCK";
char cipher[8][20]; /*cipher arranges characters under megabuck*/
int seq[8]; /*holds MEGABUCK in alphabetical weights ie
13/28
CCN Lab Manual

MEGABUCK
6 3 4 0 1 7 2 5*/
int i,j,cnt,c;
/*to get 63401725*/
/*compare each character of word with every other char and keep
count of number of characters is bigger than.. i.e. A will be greater
than 0 characters B will be greater than 1 character i.e. A so 1 and so
on...*/
for(i=0;i<strlen(wrd);++i)
{
cnt=0;
for(j=0;j<strlen(wrd);++j)
if(wrd[i]>wrd[j])
++cnt;
seq[i]=cnt;
}
printf("\nEnter data:");gets(data);
cnt=strlen(data);
/* Arrange data under megabuck in order */
for(i=0;i<cnt;++i)
/* i%strlen(wrd) will correspond to column number i.e. changes
from 0-7 and back 0-7 as i goes from 0 to cnt-1 resetting to 0 at very
8th char
i/strlen(wrd) will go as 0,1,2,3,4, changing by 1 at every 8th character
*/
cipher[i%strlen(wrd)][i/strlen(wrd)]=data[i];
if(i%strlen(wrd)!=0) /*if last line is not full*/
{
for(j=i%strlen(wrd);j<strlen(wrd);++j) /*till last char fill with
'.'*/
{ cipher[j][i/strlen(wrd)]='.'; ++cnt; }
}
printf("\nEncrypted data : \n");
for(i=0;i<strlen(wrd);++i)
{
for(c=0;c<strlen(wrd);++c)
if(seq[c]==i) break;
/*find index of value to print first under A i.e. 0 so as i=0 find which
seq[c] is 0 print that
next we search for i=2 or for 2 in seq[c] this is printed out and so on*/
14/28
CCN Lab Manual

for(j=0;j<cnt/strlen(wrd) || j==0;++j)
printf("%c",cipher[c][j]);
}
}

Output:
Enter data: PLEASE TRANSFER ONE MILLION DOLLARS TO MY
SWISS BANK
ACCOUNT SIX TWO TWO
Encrypted data :
AS WKTOSFMDTI RLL SCIWLANOR AUTENENSSNNWT LLM
CXOPROIAYBO
EEIOOSAST

4b.Decryption of a given message by Transposition Method

Algorithm for Decryption by Transposition Method


1. Get sequence of characters in word i.e. MEGABUCK
2. Get data to be decoded.
3. See if input has a multiple of length of word characters. If its not a
multiple, print that it is an error and quit.
4. Find position of first character i.e. A
5. Put size of data/size of word characters underneath it.
6. Do 4-5 for all characters of MEGABUCK in alphabetical order.
7. Print all characters row wise starting from M to K.

/* Decryption by Transposition method */


# include<stdio.h>
# include<string.h>
void main()
{
char wrd[]="MEGABUCK";
char data[100];
char cipher[8][20];
int seq[8];
int i,j,cnt,c;
for(i=0;i<strlen(wrd);++i)
{
cnt=0;
for(j=0;j<strlen(wrd);++j)
15/28
CCN Lab Manual

if(wrd[i]>wrd[j])
++cnt;
seq[i]=cnt;
}
/*get weights of MEGABUCK*/
printf("\nEnter data:");gets(data);
cnt=strlen(data);
if(cnt%strlen(wrd)!=0) /*if input is not a multiple of 8 for megabuck*/
printf("Error invalid input");
else
{
for(i=0;i<strlen(wrd);++i)
{
for(c=0;c<strlen(wrd);++c)
if( seq[c]==i) break;
/* Find location where data should be placed i.e. column to place data
under for 24 letters input there will 4 rows or 0,1,2,3 indices got by
cnt/strlen(wrd). ‘i’
indicates which column weight to feed data under and also number of
cnt/strlen(wrd) set
of characters have been placed already so now as cnt/strlen(wrd) is 4 for 24
chars... for
first row 0-3 chars are placed next 4-7 (ie cnt/strlen(wrd) which is 4) + j
where j goes
from 0 to cnt/strlen(wrd) */
for(j=0;j<cnt/strlen(wrd);++j)
cipher[c][j]=data[i*(cnt/strlen(wrd))+j];
}
for(j=0;j<strlen(wrd);++j) /* replace trailing '.' with ' ' */
{
if(cipher[j][cnt/strlen(wrd)-1]=='.')
cipher[j][cnt/strlen(wrd)-1]=' ';
}
printf("\nDecrypted data : \n");
for(i=0;i<cnt;++i) /* print out row wise */
printf("%c",cipher[i%strlen(wrd)][i/strlen(wrd)]);
}
}

Output:
16/28
CCN Lab Manual

Enter data: AS WKTOSFMDTI RLL SCIWLANOR AUTENENSSNNWT


LLM
CXOPROIAYBO EEIOOSAST
Decrypted data :
PLEASE TRANSFER ONE MILLION DOLLARS TO MY SWISS BANK
ACCOUNT SIX
TWO TWO

5.Compute Polynomial Code Checksum for CRC-CCITT


The polynomial code (also known as a cyclic redundancy code or
CRC code) is widely used. Polynomial codes are based upon treating bit
strings as representations of polynomials with coefficients of 0 and 1 only. A
k-bit frame is regarded as the coefficient list for a polynomial with k terms,
ranging from xk-1 to x0. Such a polynomial is said to be of a degree k-1.
The high-order (left most) bit is the coefficient of xk-1; the next bit is the
coefficient of xk-2, and so on. For example, 110001 has 6 bits and thus
represents a six-term polynomial with coefficients 1,1,0,0,0 and 1 : x5 + x4
+ x0. When the polynomial code method is employed, the sender and
receiver must agree upon a generator polynomial, G(x), in advance. Both the
high and low-order bits of the generator must be 1. To compute the
checksum for some frame with m bits, corresponding to the polynomial
M(x), the frame must be longer than the generator polynomial. The idea is to
append a checksum to the end of the frame in such a way that the
polynomial represented by the checksummed frame is divisible by G (x).
When the receiver gets the checksummed frame, it tries dividing it by G(x).
If there is a remainder, there has been a transmission error.

The algorithm for computing checksum is as follows:


1. Let r be the degree of G(x). Append r zero bits to the low-order end of the
frame, so it now contains m+r bits and corresponds to the polynomial xr
M(x).
2. Divide the bit string corresponding to G(X) into the bit string c
orresponding to xr M(x) using modulo-2 division.
3. Subtract the remainder (which is always r or fewer bits) from the bit string
corresponding to xr M(x) using modulo-2 subtraction. The result is the
17/28
CCN Lab Manual

checksummed frame to be transmitted. Call its polynomial T(x).


The CRC-CCITT polynomial is x16 + x12 + x5 + 1

/* C Program to compute polynomial code checksum */


# include <stdio.h>
# include <conio.h>
# define DEGREE 16 /* Degree of the generator polynomial */

int result[30];

int mod2add(int x,int y) /* Function to perform mod-2 addition */


{
return (x==y ? 0 : 1);
}

int getnext(int array[],int pos)


{
int i=pos;
/* Checking of the bits are all zeros and skipping */
while(array[i]==0)
++i;
return i;
}

void calc_CRC(int length)


{
int ccitt[]={1,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,1}; /* Generator polnomial
*/
int i=0,pos=0,newpos;
while(pos<length-DEGREE)
{
/* Performing mod-2 division for DEGREE number of bits */
for (i=pos;i<pos+DEGREE+1;++i)
result[i]=mod2add(result[i],ccitt[i-pos]);
newpos=getnext(result,pos);
/* Skipping the mod-2 division if lesser than DEGREE bits are
available
for division */
pos=newpos;
}
18/28
CCN Lab Manual

void main()
{
int array[30],ch;
int length,i=0;
clrscr();
/* Inputting data */
printf("Enter the data stream : ");
while((ch=getche())!='\r')
array[i++]=ch-'0';
length=i;
/* Appending zeros */
for (i=0;i<DEGREE;++i)
array[i+length]=0;
length+=DEGREE;
/* Duplicating the data input */
for (i=0;i<length;i++)
result[i]=array[i];
calc_CRC(length); /* Calculation of CRC */
printf("\nThe transmitted frame is : ");
for (i=0;i<length-DEGREE;++i) /* Printing the data */
printf("%d ",array[i]);
for (i=length-DEGREE;i<length;++i) /* Printing the checksum */
printf("%d ",result[i]);
printf("\nEnter the stream for which CRC has to be checked : ");
i=0;
/* Inputting the stream to be checked */
while((ch=getche())!='\r')
array[i++]=ch-'0';
length=i;
/* Duplicating the array */
for (i=0;i<length;i++)
result[i]=array[i];
calc_CRC(length); /* Calculation of CRC */
printf("\nChecksum : ");
for (i=length-DEGREE;i<length;++i) /* Printing the checksum */
printf("%d ",result[i]);
getch();
}
19/28
CCN Lab Manual

Output:
Enter the data stream : 10011
The transmitted frame is : 1 0 0 1 1 0 0 1 0 0 0 1 0 0 1 0 1 0 0 1 0
Enter the stream for which CRC has to be checked :
100110010001001010010
Checksum : 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

6. Simulate the Shortest Path Algorithm


All packets need to be routed form the source to the destination and in
most cases multiple hops are required. Routing algorithms are required to
decide on which output line an incoming packet should be forwarded onto.
Two types of routing algorithms now come in - one where the decision is
fixed and one where the route is constantly being recalculated for the best
route in other words static and dynamic routing algorithms or Non-Adaptive
and Adaptive algorithms. Routing algorithms can be made to adapt to
average traffic/loss/delay/distance /queue length etc. Dijkstra's method of
computing the shortest path or shortest path routing is a static routing
algorithm. It involves building a graph of the subnet, with each node of the
graph representing a router and each arc representing a communication line
or a link. To find a route between a pair of routers, the algorithm just finds
the shortest path between them on the graph. In Dijkstra's algorithm the
metric used for calculation is distance. Each node is labeled with its distance
from the source node along with the previous node in the path. Initially no
paths are known so all nodes are labeled with infinity. As the algorithm
proceeds and paths are found, the labels may change, reflecting better paths.
A label maybe either tentative or permanent. Initially all nodes are tentative
and once it is discovered that the shortest possible path to a node is got it is
made permanent and never changed after that.

Algorithm
1. Input graph data
2. Make all nodes TENTATIVE.
2. Input source, destination
3. Make source, the working node
4. Make the working node PERMANENT.
5. Check all tentative nodes, which are connected to working node. Update
20/28
CCN Lab Manual

weight if required.
6. Find TENTATIVE node with smallest weight. Make this the new working
node.
7. If working node is destination, go to step 8 else go to step 4
8. Trace back from destination to source.

/* Program to calculate one Shortest Path – Tanenbaum approach*/


# include<stdio.h>
# include<conio.h>
/*Total number of nodes in network*/
# define NUM_OF_NODES 10
/*State of each node*/
# define PERMANENT 1
# define TENTATIVE 0
struct node
{
unsigned int weight; /*weight of node therefore -1 is max value*/
int prev; /*previous node or is connected to*/
int state; /*state of the node*/
};
void main()
{
int table[NUM_OF_NODES][NUM_OF_NODES] =
{ /* A B C D E F G H I J*/
/*A*/ {0,1,0,0,0,4,0,0,0,0},
/*B*/ {1,0,4,0,0,0,0,1,0,0},
/*C*/ {0,4,0,3,2,0,0,0,3,0},
/*D*/ {0,0,3,0,1,0,0,0,0,0},
/*E*/ {0,0,2,1,0,3,0,0,0,1},
/*F*/ {4,0,0,0,3,0,1,0,0,0},
/*G*/ {0,0,0,0,0,1,0,2,0,2},
/*H*/ {0,1,0,0,0,0,2,0,1,0},
/*I*/ {0,0,3,0,0,0,0,1,0,2},
/*J*/ {0,0,0,0,1,0,2,0,2,0}
};/* A B C D E F G H I J*/
/*interpret as A is connected to B at a weight of 1 as
table[A][B]=table[B][A]=1*/
int src,dest,i,working_node;
/*src is source, dest is destination*/
unsigned int min;
21/28
CCN Lab Manual

struct node nodes[NUM_OF_NODES];

/*initialize all nodes as tentative and having weight of -1 or maximum*/


for(i=0;i<NUM_OF_NODES;++i)
{
nodes[i].state=TENTATIVE;
nodes[i].weight=-1;
}
printf("\nEnter Source:");
src=getche();
/*convert src character to uppercase then subtract 'A' from it
to get src index*/
working_node=src=toupper(src)-'A';
/*source is working node initially and has prev=-1 and weight=0*/
nodes[src].prev=-1;
nodes[src].weight=0;
printf("\nEnter Destination:");
dest=toupper(getche())-'A';
do
{
/*make working node permanent*/
nodes[working_node].state=PERMANENT;
for(i=0;i<NUM_OF_NODES;++i)
{
if(table[working_node][i]!=0 &&
nodes[i].state==TENTATIVE)
{
/*if connection exists and Node i is tentative*/
if(nodes[working_node].weight+table[working_no
de][i]
<nodes[i].weight)
{
/*If lesser weight is achieved with this node as
previous node*/
nodes[i].weight=nodes[working_node].weight+
table[working_node][i];
nodes[i].prev=working_node;
/*update weight and previous node*/
}
22/28
CCN Lab Manual

}
}
/*Find minimum weighted Tentative node*/
min=-1;
for(i=0;i<NUM_OF_NODES;++i)
{
if(nodes[i].state==TENTATIVE && nodes[i].weight<min)
{
min=nodes[i].weight;
working_node=i;
}
}
}while(working_node!=dest);
/*print shortest path by traversing back through node::prev*/
printf("\nShortest Path got--->\n%c",dest+65);

do
{
working_node=nodes[working_node].prev;
printf("<-%c",working_node+65);
}while(nodes[working_node].prev!=-1);
printf("\nAt a total weight of:%d",nodes[dest].weight);
}

Output:
Enter Source:A
Enter Destination:D
Shortest Path got--->
D<-E<-J<-I<-H<-B<-A
At a total weight of: 7

23/28
CCN Lab Manual

7. Find Minimum Spanning Tree of a Subset


A spanning tree is a graph is just a sub-graph that contains all the
vertices and is a tree. A graph may have many spanning trees. For instance, a
complete graph of 4 nodes can have 16 spanning trees. Suppose the edges of
the graphs have weights or lengths, the weight of tree is the sum of its edges.
Obviously, different trees have different lengths. A spanning tree includes
all the routers but contains no loops. If each router knows which of its lines
belong to the spanning tree, it can copy an incoming broadcast packet onto
all the spanning tree lines except the one it arrived on. This method makes
excellent use of bandwidth, generating the absolute minimum number of
packets necessary to do the job. The only problem is that each router must
have knowledge of some spanning tree for it to be applicable. Sometimes
this information is available (e.g. with link state routing) but sometimes it is
not (e.g. with distance vector routing).

Finding the minimum spanning tree


The easiest to understand and probably the best one for solving problems by
hand is Kruskal’s algorithm.
1. Input number of vertices
2. Input the edge weights
3. Sort the edge weights in ascending order
4. Pick the lowest edge and join the corresponding vertices
5. Repeat till edges are marked making sure that there are no closed loops
(number of vertices –1)
6. Display selected edges.

NOTE: In the program given, the variable ‘set’ is used to eliminate closed
loops. Before joining two nodes, each node’s ‘set’ is checked and if found to
be the same, the join is not performed. If the nodes are of different ‘sets’
then they are joined and then made of the same set.

/* Program for finding the Minimum Spanning Tree of a network */


#include<stdio.h>
#include<conio.h>

struct node
{
int set; /*Attribute to indicate which connection the node belongs to*/
}node[10];

24/28
CCN Lab Manual

struct edge
{
int first_node, second_node;
int distance; /* distance between the nodes*/
int selected; /* To denote whether edge is seleted*/
}e[10];

int edge_count = 0;

void getdata( int index, int total) /* Function to input the distance*/
{
int i;
for(i=index; i<total; ++i)
{
if(i!= index)
{
printf("Enter distance between vertex %c and %c:",
index+65,
i+65);
scanf("%d", &e[edge_count].distance);

e[edge_count].first_node=index;
e[edge_count].second_node=i;
e[edge_count].selected= -1;

/* If no connection between nodes */


if(e[edge_count].distance==0)
--edge_count;

++edge_count;
}
}
}

void sort_edges() /* Sort using Bubble sort */


{
int i,j;
struct edge temp;
for(i=0; i<edge_count-1; ++i)
for(j=0; j<edge_count-i-1; ++j)
25/28
CCN Lab Manual

{
{ if(e[j].distance > e[j+1].distance)
{
temp=e[j];
e[j]=e[j+1];
e[j+1]=temp;
}
}
}
}

void main()
{
int total_vertices,i,j,k,m,n,edges_selected=0,nodeL,nodeR,cost=0;
clrscr();
printf("\nEnter the no. of vertices:");
scanf("%d", &total_vertices);

for(i=0; i<total_vertices; ++i)


{
node[i].set = i;
getdata(i, total_vertices);
}
sort_edges();
printf("\n Sorted order of the edges\n");
for(i=0; i<edge_count; ++i)
printf("\nEdge: %d First:%c Second:%c Distance:%d",
i, e[i].first_node+65, e[i].second_node+65, e[i].distance);

/*Finding minimum spanning tree*/


i=0;
do
{
e[i].selected = 1; /* Edge is selected */
nodeL = e[i].first_node; /* Node on left of the edge */
nodeR = e[i].second_node; /* node on the right of the edge */

/* If the set value is the same do not select that edge */


if(node[nodeL].set == node[nodeR].set)
e[i].selected = -1; /* Deselect the edge */
26/28
CCN Lab Manual

else
{
edges_selected++;
m = node[nodeL].set;
k = node[nodeR].set;

for(n=0; n<total_vertices; ++n)


{ /* Making all nodes of the same set */
if(node[n].set == k)
node[n].set = m;
}
}
++i;
}
while(edges_selected < (total_vertices-1)); /* Check till total nodes-1
edges are formed */

printf("\n\n Minimum spanning tree:\n");


for(i=0; i<edge_count;++i)
if(e[i].selected == 1)
{
cost+= e[i].distance;
printf("\n %c<--->%c Distance:%d",

e[i].first_node+65,e[i].second_node+65,e[i].distance);
}
printf("\n\n Cost = %d", cost);
getch();
}

OUTPUT:

Output:
Enter the number of vertices: 4
Enter distance between vertex A and B: 7
Enter distance between vertex A and C: 0
Enter distance between vertex A and D: 4
Enter distance between vertex B and C: 3
Enter distance between vertex B and D: 2

27/28
CCN Lab Manual

Enter distance between vertex C and D: 1

Sorted order of edges:


Edge: 0 First Node: C Seconde Node: D Distance: 1
Edge: 1 First Node: B Seconde Node: D Distance: 2
Edge: 2 First Node: B Seconde Node: C Distance: 3
Edge: 3 First Node: A Seconde Node: D Distance: 4
Edge: 4 First Node: A Seconde Node: B Distance: 7

Minimal Spanning Tree:

C<-->D Distance: 1
B<-->D Distance: 2
A<-->D Distance: 4

Cost: 7

28/28

Potrebbero piacerti anche