Вы находитесь на странице: 1из 27

P. E. S.

INSTITUTE OF TECHNOLOGY
Department of Electronics and Communication
(Session: Aug 08 Dec 08)

CCN LABORATORY MANUAL


CCN Programming using C/C++ (3 Lab Sessions)
1. Simulate bit/character stuffing and de-stuffing in HDLC
2. Simulate the Shortest Path Algorithm
3. Encryption and Decryption of a given message
4. Find Minimum Spanning Tree of a Subnet
5. Compute Polynomial Code Checksum for CRC-CCITT

CCN Experiments using Hardware (1 Lab Session)


6. Asynchronous and Synchronous Communication using RS232 / Optical Fiber /
Twisted Pair / RJ45

CCN Lab Manual

CYCLE OF EXPERIMENTS
Cycle I [CCN programming]
1. Simulate bit/character stuffing & de-stuffing using HDLC
2. Simulate the Shortest Path
3. Algorithm
4. Encryption and Decryption of a given message
5. Find Minimum Spanning Tree of a Subset
6. Compute Polynomial Code Checksum for CRC-CCITT

Cycle II [CCN Hardware]


7. Asynchronous and Synchronous Communication using RS232 / Optical Fiber /
Twisted Pair / RJ45

2/27

Dept of ECE

CCN Lab Manual

CCN Programming using C/C++


1. Simulate bit/character stuffing and de-stuffing in HDLC
Framing involves identifying the beginning and end of a block of information within a
digital stream. Framing assumes that there is enough synchronization at the physical layer
to at least identify an individual bit or byte.In asynchronous data transmission , since
transmissions do not occur at regular intervals , the receiver resynchronizes at the start of
each eight bit character by the use of a start bit that precedes and a stop bit that ends each
character .
In synchronous data transmission bits are transmitted at regular intervals and the receiver
has the circuitry that recovers and tracks the frequency and bit transitions of the received
data
Framing may involve delineating the boundaries between frames that are of fixed length
or it may involve delineating between frames that are of variable length.
Variable length frames need more information to delineate . The methods available
include :
 Special characters to identify beginning and end of frame
 Special bit patterns-flags to identify the beginning and end of frames and
character counts
Bit Stuffing:
Flag based synchronization was developed to transfer an arbitrary number of bits within a frame.
The figure below shows the structure of an HDLC frame . The beginning and end of an HDLC
frame is indicated by the presence of an eight bit flag. The flag in HDLC consists of the byte
01111110 that is HEX 7E . Bit stuffing prevents the occurrence of the flag inside the frame. The
transmitter examines the contents of the frame and inserts an extra 0 after each instance of five
consecutive 1s. The transmitter then attaches the flag at the beginning and end of the resulting bit
stuffed frame. The receiver looks for five consecutive 1s in the received sequence. Five 1s
followed by a 0 indicate that the 0 is a stuffing bit and so the bit is removed. Five consecutive 1s
followed by 10 indicate a flag. Five 1 s followed by 11 indicate an error
The example below show bit stuffing in HDLC

3/27

Dept of ECE

CCN Lab Manual

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
4/27

Dept of ECE

CCN Lab Manual

No:
Set count to 0
4. Add stop of frame bits to output 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 */
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;
5/27

Dept of ECE

CCN Lab Manual

}
}
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

Byte stuffing:
Character based frame synchronization methods are used when the information in a frame
consists of an integer number of characters. For example, asynchronous transmission systems are
used extensively to transmit sequences of printable characters using 8 bit ASCII code . To
delineate a frame of characters, special eight bit codes that do not correspond to printable
characters are used as control characters. In ASCII code all characters with hexadecimal values
less than 20 correspond to non printable characters.
In particular STX (start of text ) control character has hex value 02 and indicates the beginning of
a frame and an ETX ( end of text ) character has HEX value 03 and denotes the end of a frame .
This method works if the frame contains only printable characters. If a frame carries computer
data, then it is possible that an ETX character will appear inside the frame and cause the receiver
to prematurely truncate the frame.This method is not transparent because the frame cannot carry
all possible bit sequences
The use of byte stuffing enables transparent operation. Byte stuffing operates as follows . A
special DLE ( data link escape) control with hex value 10 is introduced. The two character
sequence DLESTX is used to indicate the beginning of a frame and DLE ETX denotes the end of
a frame. The receiver looks for these character pairs to identify the beginning and end of
frames.In order to deal with the occurrence of DLE STX or DLE ETX in the data contained in
the frame, an extra DLE is inserted or stuffed before the occurrence of a DLE inside the frame.
Consequently every legitimate DLE in the data is replaced by two DLEs. The only incidence of
an individual DLE occurs when DLE precedes the STX or the ETX that identify the beginning
and end of the frame

6/27

Dept of ECE

CCN Lab Manual

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
4. Add stop of frame chars to output sequence
/* Program to demonstrate character stuffing */
# include <stdio.h>
# include <conio.h>
# define DLE 16
# 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')
7/27

Dept of ECE

CCN Lab Manual

{
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)
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/27

Dept of ECE

CCN Lab Manual

2. To Simulate the Shortest Path Algorithm


In order to transfer packets from a source host to the destination host , the network layer
must determine the path or route that the packets are to follow. This is the job of the
network layer routing protocol.At the heart of any routing protocol is the routing
algorithm that determines the path for a packet from source router to destination router.
Given a set of routers, with links connecting the routers, a routing algorithm finds a good
path from source router to destination router, according to some cost criterion. These can
be
1. Hop count : 1/ capacity: The cost is inversely proportional to the link capacity .
One assigns higher costs to lower capacity links . The objective is to send a packet
through a path through a path with the highest capacity. If each link has equal
capacity , then the shortest path is the path with the minimum number of hops
2. Transmission speed: The speed at which the various links operate is an important
part of a routes efficiency. Faster links obviously take precedence over slow
ones.
3. Congestion : Network congestion caused by the current traffic pattern is
considered when evaluating a route and links that are overly congested are
bypassed
4. Route cost : The route cost is a metric assigned by the network administrator used
to rate the relative usability of various routes . The cost can refer to the literal
financial expense incurred by the link or any other pertinent factor.
5. Packet delay: The cost is proportional to an average packet delay which includes
queuing delay in the switch buffer ad propagation delay in the link. The shortest
path represents the fastest path to reach the destination
Dijkstras algorithm:
Dijkstras algorithm progressively identifies the closest nodes from the source node in
order of increasing path cost. The algorithm is iterative. . The Dijkstras algorithm
calculates the shortest path between two points on a network using a graph made up
of nodes and edges The algorithm divides the nodes into two sets : tentative and
permanent . It chooses nodes, makes them tentative, examines them and if they pass
the criteria makes them permanent.
The algorithm has the following steps
1. Start with the local node (router): the root of the tree
2. Assign a cost of 0 to this node and make it the first permanent node
3. Examine each neighbour of the node that was the last permanent node
4. Assign a cumulative cost to each node and make it tentative
5. Among the list of tentative nodes
(i)
Find the node with the smallest cumulative cost and make it
permanent
(ii)
If a node can be reached from more than one direction
Select the direction with the shortest cumulative cost
6.

Repeat steps 3 to 5 until every node becomes permanent

9/27

Dept of ECE

CCN Lab Manual

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
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;
struct node nodes[NUM_OF_NODES];

10/27

Dept of ECE

CCN Lab Manual

/*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_node][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*/
}
}
}
/*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
11/27

Dept of ECE

CCN Lab Manual

{
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

12/27

Dept of ECE

CCN Lab Manual

3. Encryption and Decryption of a given message


The science and art of manipulating messages to make them secure is called
cryptography. An original message to be transformed is called the plain text and the
resulting message after the transformation is called the cipher text . The process of
converting the plain text into cipher text is called encryption. The reverse process is
called decryption. The algorithm used for encryption and decryption is often called a
cipher
Substitution ciphers are a common technique for altering messages in games and
puzzles. Each letter of the alphabet is mapped into another letter. The cipher text is
obtained by applying the substitution defined by the mapping to the plain text
Transposition ciphers are an other type of encryption scheme . Here the order in
which the letters appear is altered. The letters may be written into an array in one order
and read out in a different order.
Substitution and transposition techniques are easily broken
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 cipher text, is then transmitted, often by messenger or radio. We
assume that the enemy or intruder, hears and accurately copies down the complete cipher
text. However, unlike the intended recipient, he does not know what the decryption key is
and so cannot decrypt the cipher text 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
13/27

Dept of ECE

CCN Lab Manual

This general system is called a mono-alphabetic substitution, with the key being the 26letter 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
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 datas 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]*/
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!
14/27

Dept of ECE

CCN Lab Manual

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 datas 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*/
{
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';
15/27

Dept of ECE

CCN Lab Manual

printf("\nDecoded string is : %s",decoded);


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

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 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:

AFLLSKSOSELAWAIATOOSSCTCLNMOMANTESILYNTWRNNTSOWDPAE
DOBUOERIRICXB
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 arent done
/* Encryption by Transposition method */
# include<string.h>
# include<stdio.h>
void main()
{
16/27

Dept of ECE

CCN Lab Manual

char data[100];
char wrd[]="MEGABUCK";
char cipher[8][20]; /*cipher arranges characters under megabuck*/
int seq[8]; /*holds MEGABUCK in alphabetical weights ie
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*/
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

17/27

Dept of ECE

CCN Lab Manual

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)
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 ' ' */
{
18/27

Dept of ECE

CCN Lab Manual

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:
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

19/27

Dept of ECE

CCN Lab Manual

4. Find Minimum Spanning Tree of a Subset

In graph theory , a spanning tree is a graph in which there is no loop . In a bridged LAN ,
this means creating a topology in which each LAN can be reached from any other LAN
through one path only(no loops). This is done by automatically disabling certain bridges.
It is important that these bridges are not physically removed , since a topology change
may require a different set of bridges to be disabled, thus reconfiguring the spanning tree
dynamically
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).

A spanning tree of a connected graph G is a connected subgraph of G having no cycles.


Every connected graph has a spanning tree. For example, the following graph has four
distinct spanning trees.

Spanning Trees:

In general a graph will have very many spanning trees. The weight of a subgraph to be
sum of all the edge weights in the subgraph. Different spanning trees have different
weights, the minimum spanning tree is the spanning tree with the minimum weight.
Example: weights added to the graph above

spanning tree S1 has weight 3+2+4 = 9


spanning tree S2 has weight 2+4+1 = 7
spanning tree S3 has weight 3+2+1 = 6
20/27

Dept of ECE

CCN Lab Manual

spanning tree S4 has weight 3+4+1 = 8

S3 is the minimum spanning tree of this graph.


Finding the minimum spanning tree
The easiest to understand and probably the best one for solving problems by hand is
Kruskals 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 nodes 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[100];
struct edge
{
int first_node,second_node;
int distance; /* Distance between the nodes */
int selected; /* To denote whether edge is selected */
}e[100];
int edge_count=0;

void getdata(int index,int total) /* Function to input the distances */


{
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;
++edge_count;
}
21/27

Dept of ECE

CCN Lab Manual

}
}
void initialise(int total_nodes)
{
int i;
for (i=0;i<total_nodes;++i)
node[i].set = i; /* Set number to indicate loop */
for (i=0;i<edge_count;++i)
e[i].selected=-1; /* Edge not selected initially */
}
void sort_edges()
{
int i,j;
struct edge temp;
for (i=0;i<edge_count-1;++i) /* Sorting by Bubble Sort */
for (j=0;j<edge_count-i-1;++j)
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;
clrscr();
printf("Enter the number of vertices : ");
scanf("%d",&total_vertices);
for (i=0;i<total_vertices;++i)
getdata(i,total_vertices);
initialise(total_vertices); /* Initialising all nodes and edges */
sort_edges();
/* Printing sorted order of the edges */
clrscr();
printf("Sorted order of edges : ");
for (i=0;i<edge_count;++i)
printf("\nEdge : %d First Node : %c Second Node : %c Distance :
%d",i,e[i].first_node+65,e[i].second_node+65,e[i].distance);
/* Finding the minimum spanning tree */
i=0; /* Initialise i to beginning of the edge array */
do
{
e[i].selected=1; /* Edge is selected */
nodel=e[i].first_node; /* Node on the left of the edge */
noder=e[i].second_node; /* Node on the right of the edge */
/* If the set is the same do not select that edge */
if (node[nodel].set==node[noder].set)
e[i].selected=-1; /* Deselect the edge */
else
{
22/27

Dept of ECE

CCN Lab Manual

edges_selected++; /* Select the edge */


m=node[nodel].set;
k=node[noder].set;
for (n=0;n<total_vertices;++n)
{
/* Making all connected 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\nMinimal Spanning Tree : \n");/*Printing the minimum spanning tree
*/
for (i=0;i<edge_count;++i)
if (e[i].selected==1)
printf("\n%c <----> %c Distance :
%d",e[i].first_node+65,e[i].second_node+65,e[i].distance);
getch();
}
Output:
Enter the number of vertices : 6
Enter distance between vertex A and B : 2
Enter distance between vertex A and C : 5
Enter distance between vertex A and D : 6
Enter distance between vertex A and E : 3
Enter distance between vertex A and F : 4
Enter distance between vertex B and C : 3
Enter distance between vertex B and D : 6
Enter distance between vertex B and E : 3
Enter distance between vertex B and F : 6
Enter distance between vertex C and D : 4
Enter distance between vertex C and E : 5
Enter distance between vertex C and F : 7
Enter distance between vertex D and E : 4
Enter distance between vertex D and F : 6
Enter distance between vertex E and F : 4
Sorted order of edges :
Edge : 0 First Node : A Second Node : B Distance : 2
Edge : 1 First Node : A Second Node : E Distance : 3
Edge : 2 First Node : B Second Node : C Distance : 3
Edge : 3 First Node : B Second Node : E Distance : 3
Edge : 4 First Node : A Second Node : F Distance : 4
Edge : 5 First Node : C Second Node : D Distance : 4
Edge : 6 First Node : D Second Node : E Distance : 4
Edge : 7 First Node : E Second Node : F Distance : 4
Edge : 8 First Node : A Second Node : C Distance : 5
Edge : 9 First Node : C Second Node : E Distance : 5
23/27

Dept of ECE

CCN Lab Manual

Edge : 10 First Node : A Second Node : D Distance : 6


Edge : 11 First Node : B Second Node : D Distance : 6
Edge : 12 First Node : B Second Node : F Distance : 6
Edge : 13 First Node : D Second Node : F Distance : 6
Edge : 14 First Node : C Second Node : F Distance : 7
Minimal Spanning Tree :
A <----> B Distance : 2
A <----> E Distance : 3
B <----> C Distance : 3
A <----> F Distance : 4
C <----> D Distance : 4

24/27

Dept of ECE

CCN Lab Manual

5. Compute Polynomial Code Checksum for CRC-CCITT


Polynomial codes are extensively used in error detection and correction.
Polynomial codes are readily implemented using shift register circuits and therefore are
the most widely implemented error control codes. Polynomial codes involve generating
check bits in the form of a cyclic redundancy check (CRC). They are also known as CRC
codes.
In polynomial codes the information symbols , the code words and the error
vectors are represented by polynomials with binary coefficients. The k information bits
(ik-1, ik-2 , .i1, i0) are used to form the information polynomial of degree (k-1)
i(x) = ik-1 xk-1 + ik-2 xk-2 + + i1 x + i0
The encoding process takes i(x) and produces a codeword polynomial b(x) that
contains the information bits and additional check bits and that satisfies a certain
pattern. To detect errors , the receiver checks to see whether the pattern is satisfied
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 sixterm 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 corresponding 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
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];
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 */
25/27

Dept of ECE

CCN Lab Manual

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 */
if (newpos>pos+1)
pos=newpos-1;
++pos;
}
}
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;
}
int mod2add(int x,int y) /* Function to perform mod-2 addition */
{
return (x==y ? 0 : 1);
}
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;
26/27

Dept of ECE

CCN Lab Manual

/* 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();
}
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

27/27

Dept of ECE

Вам также может понравиться