Professional Documents
Culture Documents
TECHNOLOGY
ICHCHANATH, PIPLOD, SURAT-395007
LABORATORY MANUAL
B. TECH III-SEMESTER VI
BATCH: A3
SARDAR VALLABHBHAI NATIONAL INSTITUTE OF
TECHNOLOGY
ICHCHANATH, PIPLOD, SURAT-395007
CERTIFICATE
SUBJECT CO-ORDINATOR
DATE: 28-04-2021
INDEX
SI
SR. PAGE
DATE PRACTICAL NAME G
NO. NO.
N
AIM: To study TCP/IP protocol stack and some network management commands like IPCONFIG,
PING and TRACERT.
Application
L ayer
Transport L ayer
Network L ayer
P h ysical Layer
Network Frame
SYNTAX:
ipconfig [/all] [/renew [Adapter]] [/release [Adapter]] [/flushdns] [/displaydns] [/registerdns]
[/showclassid Adapter] [/setclassid Adapter [ClassID]]
PARAMETERS:
/all: Displays the full TCP/IP configuration for all adapters. Without this parameter, ipconfig
displays only the IP address, subnet mask, and default gateway values for each adapter.
Adapters can represent physical interfaces, such as installed network adapters, or logical
interfaces, such as dial-up connections.
/renew [Adapter]: Renews DHCP configuration for all adapters (if an adapter is not specified) or
for a specific adapter if the Adapter parameter is included, this parameter is available only on
computers with adapters that are configured to obtain an IP address automatically. To specify
an adapter name, type the adapter name that appears while using ipconfig without parameters.
/release [Adapter]: Sends a DHCPRELEASE message to the DHCP server to release the current
DHCP configuration and discard the IP address configuration for either all adapters (if an
adapter is not specified) or for a specific adapter if the Adapter parameter is included. This
parameter disables TCP/IP for adapters configured to obtain an IP address automatically. To
specify an adapter name, type the adapter name that appears while using.
/flushdns: Flushes and resets the contents of the DNS client resolver cache. During DNS
troubleshooting, one can use this procedure to discard negative cache entries from the cache,
as well as any other entries that have been added dynamically.
/displaydns: Displays the contents of the DNS client resolver cache, which includes both entries
preloaded from the local Hosts file and any recently obtained resource records for name
queries resolved by the computer. The DNS Client service uses this information to resolve
frequently queried names quickly, before querying its configured DNS servers.
/registerdns: Initiates manual dynamic registration for the DNS names and IP addresses that
are configured at a computer. You can use this parameter to troubleshoot a failed DNS name
registration or resolve a dynamic update problem between a client and the DNS server without
rebooting the client computer. The DNS settings in the advanced properties of the TCP/IP
protocol determine which names are registered in DNS.
/showclassid Adapter: Displays the DHCP class ID for a specified adapter, to see the DHCP class
ID for all adapters, use the asterisk (*) wildcard character in place of Adapter. This parameter is
available only on computers with adapters that are configured to obtain an IP address
automatically.
/setclassid Adapter [ClassID]: Configures the DHCP class ID for a specified adapter. To set the
DHCP class ID for all adapters, use the asterisk (*) wildcard character in place of Adapter. This
parameter is available only on computers with adapters that are configured to obtain an IP
address automatically. If a DHCP class ID is not specified, the current class ID is removed.
EXAMPLES:
To display the basic TCP/IP configuration for all adapters, type:
ipconfig
To renew a DHCP-assigned IP address configuration for only the Local Area Connection adapter,
type:
To flush the DNS resolver cache when troubleshooting DNS name resolution problems, type:
ipconfig /flushdns
To display the DHCP class ID for all adapters with names that start with Local, type:
ipconfig /showclassid Local*
To set the DHCP class ID for the Local Area Connection adapter to TEST, type:
ipconfig /setclassid "Local Area Connection" TEST
2. PING:
SYNTAX:
ping [-t] [-a] [-n Count] [-1 Size] [-f] [-i TTL] [-v TOS] [-r Count] [-s Count] H-j HostList I k
HostList}] [-w Timeout] [TargetName].
PARAMETERS:
-t : Specifies that ping continue sending Echo Request messages to the destination until
interrupted. To interrupt and display statistics, press CTRL-BREAK, To interrupt and quit ping,
press CTRL-C.
-a : Specifies that reverse name resolution is performed on the destination IP address. If this is
successful, ping displays the corresponding host name.
-n Count: Specifies the number of Echo Request messages sent. The default is 4.
-l Size: Specifies the length, in bytes, of the Data field in the Echo Request messages sent.
The default is 32. The maximum size is 65,527.
-f : Specifies that Echo Request messages are sent with the Don't Fragment flag in the IP header
set to 1. The Echo Request message cannot be fragmented by routers in the path to the
destination. This parameter is useful for troubleshooting path Maximum Transmission Unit
(PMTU) problems.
-i TTL : Specifies the value of the TTL field in the IP header for Echo Request messages sent. The
default is the default TTL value for the host. For Windows XP hosts, this is typically 128. The
maximum TTL is 255.
-v TOS : Specifies the value of the Type of Service (TOS) field in the IP header for Echo Request
messages sent. The default is 0. TOS is specified as a decimal value from 0 to 255.
-r Count: Specifies that the Record Route option in the IP header is used to record the path
taken by the Echo Request message and corresponding Echo Reply message. Each hop in the path
uses an entry in the Record Route option. If possible, specify a Count that is equal to or greater
than the number of hops between the source and destination. The count must be a minimum of
1 and a maximum of 9.
-s Count: Specifies that the Internet Timestamp option in the IP header is used to record the
time of arrival for the Echo Request message and corresponding Echo Reply message for each
hop. The Count must be a minimum of 1 and a maximum of 4.
-j HostList : Specifies that the Echo Request messages use the Loose Source Route option in
the IP header with the set of intermediate destinations specified in HostList. With loose source
routing, successive intermediate destinations can be separated by one or multiple routers. The
maximum number of addresses or names in the host list is 9. The host list is a series of IP
addresses (in dotted decimal notation) separated by spaces.
-k HostList : Specifies that the Echo Request messages use the Strict Source Route option in
the IP header with the set of intermediate destinations specified in HostList. With strict source
routing, the next intermediate destination must be directly reachable (it must be a neighbor on
an interface of the router). The maximum number of addresses or names in the host list is 9. The
host list is a series of IP addresses (in dotted decimal notation) separated by spaces.
-w Timeout: Specifies the amount of time, in milliseconds, to wait for' the Echo Reply message
that corresponds to a given Echo Request message to be received. If the Echo Reply message is
not received within the time-out, the "Request timed out" error message is displayed. The
default time-out is 4000 (4 seconds).
TargetName: Specifies the destination, which is identified either by IP address or host name.
EXAMPLES:
The following example shows ping command output:
C:\> ping example.microsoft.com
Pinging example.microsoft.com [192.168.239.132] with 32 bytes of data:
Reply from 192.168.239.132: bytes=32 time=10lms TTL=124
Reply from 192.168.239.132: bytes=32 time=100ms TTL=124
Reply from 192.168.239.132: bytes=32 time=120ms TTL=124
Reply from 192.168.239.132: bytes=32 time=120ms TTL=124
To ping the destination 10.0.99.221 and resolve 10.0.99.221 to its host name; type:
ping -a 10.0.99.221
To ping the destination 10.0.99.221 with 10 Echo Request messages, each of which has a data
field of 1000 bytes, type: ping -n 10 1000 10.0.99.221
To ping the destination 10.0.99.221 and record the route for 4 hops, type: ping -r
4 10.0.99.221
To ping the destination 10.0.99.221 and specify the loose source route of .10.12.0.1-10.29.3.1
10.1.44.1, type:
ping -j 10.12.0.1 10.29.3.1 10.1.44.1 10.0.99.221
3. TRACERT:
It is a computer network tool to determine the route taken by the packet across an IP network.
The traceroute tool is available on practically all Unix-like operating systems. Variants with
similar functionality are also available, such as tracepath on modern Linux installations and
tracert on Microsoft Windows operating systems. Windows -NT based OS also provide path
ping it Determines the path taken to a destination by sending Internet Control Message
Protocol (ICMP) Echo Request messages to the destination with incrementally increasing Time
to Live (TTL) field values. The path displayed is the list of near-side router interfaces of the
routers in the path between a source host and a destination: The near-side interface is the
interface of the router that is closest to the sending host in the path. Used without parameters,
tracert displays help. It is used for network troubleshooting. It indicates the routers traversed
and the path taken, helpful to find routing problems.
SYNTAX:
tracert [-d] [-h MaximumHops] [-j HostList] [-w Timeout] [TargetName]
PARAMETERS:
-d : Prevents tracert from attempting to resolve the IP addresses of intermediate routers to
their names. This can speed up the display of tracert results.
-h MaximumHops : Specifies the maximum number of hops in the path to search for the target
(destination). The default is 30 hops.
-j HostList : Specifies that Echo Request messages use the Loose Source Route option in the IP
header with the set of intermediate destinations specified in HostList. With loose source
routing, successive intermediate destinations can be separated by one or multiple routers. The
maximum number of addresses or names in the host list is 9. The HostList is a series of IP
addresses (in dotted decimal notation) separated by spaces.
-w Timeout : Specifies the amount of time in milliseconds to wait for the ICMP Time Exceeded
or Echo Reply message corresponding to a given Echo Request message to be received. If not
received within the time-out, an asterisk (*) is displayed. The default timeout is 4000 (4
seconds).
EXAMPLES:
To trace the path to the host named corp7.microsoft.com and prevent the resolution of each IP
address to its name, type:
tracert -d corp7.microsoft.com
To trace the path to the host named corp7.microsoft.com and use the loose source route
10.12.0.1-10.29.3.1-10.1.44.1, type:
tracert -j 10.12.0.110.29.3.110.1.44.1 corp7.microsoft.com
RESULTS:
TCP/IP protocol has been studied and network management commands were practiced with
various arguments.
ipconfig
ipconfig /?
ipconfig /all
ipconfig /renew
ipconfig /release
ipconfig /flushdns
ipconfig /displaydns
Ping 127.0.0.1
CONCLUSION:
From this experiment we can conclude that using theses three different command and their
sub-commands we can get our connected network ip-address, mac address, our device address
and our network strength or any address connecting strength.
AIM: Write a C Program to implement Cyclic Redundancy Check (CRC) method for error
detection.
THEORY:
CRC is a common method for detecting errors in transmitted messages or stored data. The CRC
is a very powerful, but easily implemented technique to obtain data reliability. There are
several formats for the implementation of CRC such as CRC-CCITT, CRC-32 or other polynomials.
The theory of a CRC calculation is straight forward. The data is treated by the CRC algorithm as
a binary number. This number is divided by another binary number called the polynomial. The
rest of the division is the CRC checksum, which is appended to the transmitted message. The
receiver divides the message (including the calculated CRC), by the same polynomial the
transmitter used. If the result of this division is zero, then the transmission was successful.
However, if the result is not equal to zero, an error occurred during the transmission.
The CRC-16 polynomial is shown in Equation 1. The polynomial can be translated into a binary
value, because the divisor is viewed as a polynomial with binary coefficients. For example, the
CRC-16 polynomial translates to 11000000000000101b. All coefficients, like x2 or x15, are
represented by a logical 1 in the binary value. The division uses the Modulo-2 arithmetic.
Modulo-2 calculation is simply realized by XOR’ing two numbers.
Example Calculation
In this example calculation, the message is two bytes long. In general, the message can have
any length in bytes. Before we can start calculating the CRC value 1, the message has to be
augmented by n-bits, where n is the length of the polynomial. The CRC-16 polynomial has a
length of 16-bits; therefore, 16-bits have to be augmented to the original message. In this
example calculation, the polynomial has a length of 3-bits; therefore, the message has to be
extended by three zeros at the end. An example calculation for a CRC is shown in Example
FLOW CHART:
C PROGRAM:
(i) Encoder Side
/*ENCODING THE GIVEN DATA*/
#include<stdio.h>
#include<conio.h>
int rem(int,int);
void main()
{
int i,j,d_len,div_len;
int data[10],divs[5],data1[15],crc[5],edata[15];
getch();
}
#include<stdio.h>
#include<conio.h>
int rem(int,int);
void main()
{
int i,j,k,d_len,div_len;
int divs[5],recdata[15],remd[5];
RESULTS:
(i) Encoder Side
CONCLUSION:
In this experiment we have implemented the Cyclic Redundancy Check(CRC) method to detect
error in data transmission. By this method we can detect error in transmission and reject the
data easily by analysing error in data before giving to the system.
AIM: Write a C Program to implement Hamming code for error detection and correction.
THEORY:
In telecommunication, a Hamming code is a linear error-correcting code. Hamming codes can
detect up to two simultaneous bit errors, and correct single-bit errors; thus, reliable
communication is possible when the Hamming distance between the transmitted and received
bit patterns is less than or equal to one. By contrast, the simple parity code cannot correct
errors, and can only detect an odd number of errors.
Because of the simplicity of Hamming codes, they are widely used in computer memory (RAM).
In particular, a single-error-correcting and double-error-detecting variant commonly referred to
as SECDED.
1. Mark all bit positions that are powers of two as parity bits. (Positions 1, 2, 4, 8, 16, 32, 64, etc.)
2. All other bit positions are for the data to be encoded. (Positions 3, 5, 6, 7, 9, 10, 11, 12, 13, 14,
15, 17, etc.)
3. Each parity bit calculates the parity for some of the bits in the code word. The position of the
parity bit determines the sequence of bits that it alternately checks and skips.
Position 1: check 1 bit, skip 1 bit, check 1 bit, skip 1 bit, etc. (1, 3, 5, 7, 9, 11, 13,
15,……………)
Position 2: check 2 bits, skip 2 bits, check 2 bits, skip 2 bits, etc. (2, 3, 6, 7, 10, 11,
14, 15,……………)
Position 4: check 4 bits, skip 4 bits, check 4 bits, skip 4 bits, etc. (4, 5, 6, 7, 12, 13,
14, 15, 20, 21, 22, 23,……………)
Position 8: check 8 bits, skip 8 bits, check 8 bits, skip 8 bits, etc. (8-15, 24-31, 40-
47,……………)
Position 16: check 16 bits, skip 16 bits, check 16 bits, skip 16 bits, etc. (16-31, 48-63,
80-95,…………....)
Position 32: check 32 bits, skip 32 bits, check 32 bits, skip 32 bits, etc. (32-63, 96-
4. Set a parity bit to 1 if the total number of ones in the positions it checks is odd. Set a
parity bit to 0 if the total number of ones in the positions it checks is even.
Example:
A byte of data: 10011010 Create the data word, leaving spaces for the parity bits: _ _ 1 _ 0 0 1_
1 0 1 0 Calculate the parity for each parity bit (a ? represents the bit position being set):
Position 1 checks bits 1, 3, 5, 7, 9, 11: ? _ 1 _ 0 0 1 _ 1 0 1 0. Even parity so set position 1 to a 0:
0_1_001_1010
and correct it. The method is to verify each check bit. Write down all the incorrect parity bits.
Doing so, you will discover that parity bits 2 and 8 are incorrect. It is not an accident that 2 + 8 =
10, and that bit position 10 is the location of the bad bit. In general, check each parity bit, and
add the positions that are wrong, this will give you the location of the bad bit.
Flow Chart: -
C PROGRAM:
(a) Encoder
#include <stdio.h>
void main() {
int data[7],i;
printf("Input data = ");
scanf("%d",&data[0]);
scanf("%d",&data[1]);
scanf("%d",&data[2]);
scanf("%d",&data[4]);
data[3]=data[0]^data[1]^data[2];
data[5]=data[0]^data[1]^data[4];
data[6]=data[0]^data[2]^data[4];
printf("%d",data[i]);
(b) Decoder
#include <stdio.h>
void main() {
int rdata[7],i,c1,c2,c3,c;
printf("Recieved data = ");
for(i=0;i<7;i++)
scanf("%d",&rdata[i]);
c1=rdata[3]^rdata[0]^rdata[1]^rdata[2];
c2=rdata[5]^rdata[0]^rdata[1]^rdata[4];
c3=rdata[6]^rdata[0]^rdata[2]^rdata[4];
c=c1*4+c2*2+c3;
if(c==0)
printf("\nNO ERROR");
else {
RESULTS:
(a) Encoder
(b) Decoder
CONCLUSION:
In this experiment we have learned Hamming coding in which we add parity bits to input data
with respective corresponding data bits and make a code word at transmitter and at the
receiver side we check those parity bits and analyse whether code word is corrupted or not and
it also provide the position of error bit so that if we complement the error bit we can get the
exact data.
THEORY:
Flag fields of HDLC Frame Format delimit the frame at both ends with the unique pattern
01111110. A single flag may be used as the closing flag for one frame and the opening flag for
the next. On the both sides of the user-network interface, receivers are continuously hunting
for the flag sequence to synchronize on the start of a frame. While receiving a frame, a station
continues to hunt for that sequence to determine the end of the frame. However, it is possible
that the pattern 01111110 will appear somewhere inside the frame, thus destroying frame level
synchronization. To avoid this procedure known as bit stuffing is used. Between the
transmission of the starting and ending flags, the transmitter will always insert an extra 0 bit
after each occurrence of five 1s in the frame. After detecting a starting flag, the receiver
monitors the bit stream. When a pattern of five 1s appears, the sixth bit is examined. If this bit
is 0 it is deleted. If the sixth it is a 1 and the seventh bit is a 0, the combination is accepted as a
flag. If the sixth and seventh bits are both 1 the sender is indicating an abort condition.
With the use of bit stuffing, arbitrary bit patterns can be inserted into the data field of the
frame. This property is known as data transparency.
Figure shows an example of bit stuffing. Note that in the first two cases, the extra 0 is not
strictly necessary for the operation of the algorithm. The pitfalls of bit stuffing are also
illustrated in this figure. When a flag is used as an ending and a starting flag, a 1-bit error
merges two frames into one; conversely, a 1 bit error inside the frame could split it in two.
Original Pattern
111111111111011111101111110
After bit stuffing
11111011111011011111101011111010
FLAG FLAG
Bit Inverted
Bit Inverted
FLAG FLAG
Flow Chart: -
C PROGRAM:
(a) Encoder
#include <stdio.h>
#include<string.h>
void main()
{
int i, j,count=0,l;
char data[20];
printf("Enter Data = ");
scanf("%s",&data);
for (i=0;i<strlen(data);i++)
{
count=0;
for (j=i;j<=(i+5);j++)
{
if(data[j]=='1')
{
count++;
} }
if(count==6) {
l=strlen(data)+2;
for (;l>=(i+5);l--) {
data[l]=data[l-1];
}
data[i+5]='0';
i=i+7;
} }
printf("Stuffed Data ");
for(i=0;i<strlen(data);i++)
printf("%c",data[i]);
(b) Decoder
#include<stdio.h>
#include <string.h>
void main()
{
int i=0,count=0;
char s_data[20];
printf("Enter Stuffed Data = ");
scanf("%s",&s_data);
printf("Extracted Data = ");
for(i=0; i<strlen(s_data);i++)
{
if(s_data[i]=='1')
count++;
else
count=0;
printf("%c",s_data[i]);
if(count==5) {
s_data[i+1]=s_data[i+2];
count=0;
i=i+2;
}
}
}
RESULTS:
(a)Encoder
(b)Decoder
CONCLUSION:
In this experiment we have learned Bit Stuffing and De-Stuffing in which to avoid confusion of
which is flag part so we add 0 after continuous five 1’s and produce a stuffed code at
transmitter side and at receiver side it removes 0 after continuous five 1’s from data word.
THEORY:
Suppose you want to find the shortest path between two intersections on a map, a starting
point and a destination. To accomplish this, you could highlight the streets (tracing the streets
with a marker) in a certain order, until you have a route highlighted from the starting point to
the destination. The order is conceptually simple. At each iteration, create a set of intersections
consisting of every unmarked intersection that is directly connected to a marked intersection,
this will be your set of considered intersections. From that set of considered intersections, find
the closest intersection to the destination (this is the "greedy" part, as described above) and
highlight it and mark that street to that intersection, draw an arrow with the direction, then
repeat. In each stage mark just one new intersection. When you get to the destination, follow
the arrows backwards. There will be only one path back against the arrows, the shortest one.
For a given source vertex (node) in the graph, the algorithm finds the path with lowest cost (i.e.
the shortest path) between that vertex and every other vertex. It can also be used for finding
costs of shortest paths from a single vertex to a single destination vertex by stopping the
algorithm once the shortest path to the destination vertex has been determined. For example,
if the vertices of the graph represent cities and edge path costs represent driving distances
between pairs of cities connected by a direct road, Dijkstra's algorithm can be used to find the
shortest route between one city and all other cities. As a result, the shortest path first is widely
used in network routing protocols, most notably IS-IS and OSPF (Open Shortest Path First).
ALGORITHM
Let the node at which we are starting be called the initial node. Let the distance of node Y be
the distance from the initial node to Y. Dijkstra's algorithm will assign some initial distance
values and will try to improve them step-by-step.
1. Assign to every node a distance value. Set it to zero for our initial node and to infinity for
all other nodes.
2. Mark all nodes as unvisited. Set initial node as current.
3. For current node, consider all its unvisited neighbors and calculate their distance (from
the initial node). For example, if current node (A) has distance of 6, and an edge
connecting it with another node (B) is 2, the distance to B through A will be 6+2=8. If this
distance is less than the previously recorded distance (infinity in the beginning, zero for
the initial node), overwrite the distance.
4. When we are done considering all neighbors of the current node, mark it as visited. A
visited node will not be checked ever again; its distance recorded now is final and minimal.
5. Set the unvisited node with the smallest distance (from the initial node) as the next
"current node" and continue from step 3.
C PROGRAM:
#include<stdio.h>
#include<conio.h>
#define INFINITY 9999
#define MAX 10
void shortest_path(int G[MAX][MAX],int n,int startnode,int stopnode);
int main(){
int G[MAX][MAX],i,j,n,u,v;
printf("Enter no. of vertices:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");
for(i=1;i<n+1;i++)
for(j=1;j<n+1;j++)
scanf("%d",&G[i][j]);
printf("\nEnter the starting node:");
scanf("%d",&u);
printf("\nEnter the stop node:");
scanf("%d",&v);
shortest_path(G,n,u,v);
getch();
return 0;}
void shortest_path(int G[MAX][MAX],int n,int startnode,int stopnode){
int cost[MAX][MAX],distance[MAX],pred[MAX];
int visited[MAX],count,mindistance,nextnode,i,j;
for(i=1;i<n+1;i++)
for(j=1;j<n+1;j++){
if(G[i][j]==0)
cost[i][j]=INFINITY;
else
cost[i][j]=G[i][j]; }
for(i=1;i<n+1;i++){
distance[i]=cost[startnode][i];
pred[i]=startnode;
visited[i]=0; }
distance[startnode]=0;
visited[startnode]=1;
count=1;
while(count<n-1){
mindistance=INFINITY;
for(i=1;i<n+1;i++)
if(distance[i]<mindistance&&!visited[i]){
mindistance=distance[i];
nextnode=i;}
visited[nextnode]=1;
for(i=1;i<n+1;i++)
if(!visited[i])
if(mindistance+cost[nextnode][i]<distance[i]){
distance[i]=mindistance+cost[nextnode][i];
pred[i]=nextnode; }
count++;}
i=stopnode;
printf("\nDistance of node%d=%d",i,distance[i]);
printf("\nPath=%d",i);
j=i;
do{
j=pred[j];
printf("<-%d",j);
}while(j!=startnode);
}
RESULTS:
Input:
Output:
Shortest distance between 5→1
Input:
Output:
Shortest distance between A(1)→E(5)
CONCLUSION:
In this experiment we have implemented and verified the Y. Dijkstra's algorithm. This algorithm
is used to find the shortest path between any two nodes in the given network by fixing the
starting node.
CIPHERING TECHNIQUES
AIM: Write a C Program to implement Cipher text using classical Cipher method.
THEORY:
Ciphers
Stream Block
Substitution Cipher
In a substitution cipher, each letter or group of letters is replaced by another letter or group
of letters to disguise it. One of the oldest known ciphers is the Caesar cipher, attributed to
Julius Caesar. In this method, a becomes D, b becomes E, c becomes F, ... , and z becomes C.
For example, attack becomes DWWDFN. In examples, plaintext will be given in lower case
letters, and ciphertext in upper case letters.
A slight generalization of the Caesar cipher allows the ciphertext alphabet to be shifted by k
letters, instead of always 3. In this case k becomes a key to the general method of circularly
shifted alphabets. The Caesar cipher may have fooled Pompey, but it has not fooled anyone
since.
The next improvement 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 J K L Z X C V B N M
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. Figure 2
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 key letter
closest to the start of the alphabet, and so on. The plaintext is written horizontally, in rows,
padded to fill the matrix if need be. The ciphertext is read out by columns, starting with the
column whose key letter is the lowest.
ALGORITHM:
Algorithm for transposition cipher is:
START
END
C PROGRAM:
CAESAR CIPHER: -
a) Encryption
#include<stdio.h>
int main()
{
char message[100], c;
int i, key;
printf("Message to encrypt = ");
gets(message);
printf("key = ");
scanf("%d", &key);
for(i = 0; message[i] != '\0'; ++i){
c = message[i];
if(c >= 'a' && c <= 'z'){
c = c + key - 32;
if(c > 'Z'){
c = c - 'Z' + 'A' - 1;
}
message[i] = c;
}
}
printf("Encrypted message = %s", message);
return 0;
}
b)Decryption
#include<stdio.h>
int main()
{
char ciphertext[100], c;
int i, key;
printf("Message to decrypt = ");
gets(ciphertext);
printf("key = ");
scanf("%d", &key);
for(i = 0; ciphertext[i] != '\0'; ++i){
c = ciphertext[i];
if(c >= 'A' && c <= 'Z'){
c = c - key + 32;
if(c < 'a'){
c = c + 'z' - 'a' + 1;
}
ciphertext[i] = c;
}
}
printf("Decrypted message = %s", ciphertext);
return 0;
}
RESULTS:
a)Encryption
b)Decryption
MONOALPHABETIC CIPHER: -
a)Encryption
#include<stdio.h>
#include<conio.h>
void main()
{
char pt[30] ,c[27], ct[30];
int i, j, index;
printf("Message to encrypt = ");
gets(pt);
printf("Cipher letters = ");
gets(c);
printf("\nEnter Key From a to z : \n");
for(i = 0; i < 26; i++)
{
printf("%c-", i + 97);
printf("%c , ", c[i]);
}
for(i = 0; pt[i] != '\0'; ++i)
{
index = pt[i] - 97;
ct[i] = c[index];
}
printf("\nCipher Text = ");
for(i = 0; pt[i] != '\0'; ++i)
{
printf("%c", ct[i]);
}
}
b)Decryption
#include<stdio.h>
#include<conio.h>
void main()
{
char pt[30] ,c[27], ct[30],al[27];
int i, j, index;
printf("Message to Decrypt = ");
gets(ct);
printf("Cipher letters = ");
gets(c);
printf("alphabets = ");
gets(al);
printf("\nEnter Key From a to z : \n");
for(i = 0; i < 26; i++)
{
printf("%c-", i + 97);
printf("%c , ", c[i]);
}
for(i = 0; ct[i] != '\0'; ++i)
{
index = ct[i]-65-(c[1]-al[1]+32);
pt[i] = al[index];
}
printf("\nMessage = ");
for(i = 0; ct[i] != '\0'; ++i)
{
printf("%c", pt[i]);
}
}
RESULTS:
a)Encryption
b)Decryption
PLAYFAIR CIPHER: -
a)Encryption
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 30
void toLowerCase(char plain[], int ps)
{
int i;
for (i = 0; i < ps; i++) {
if (plain[i] > 64 && plain[i] < 91)
plain[i] += 32;
}}
int removeSpaces(char* plain, int ps)
{
int i, count = 0;
for (i = 0; i < ps; i++)
if (plain[i] != ' ')
plain[count++] = plain[i];
plain[count] = '\0';
return count;
}
void generateKeyTable(char key[], int ks, char keyT[5][5]) {
int i, j, k, flag = 0, *dicty;
dicty = (int*)calloc(26, sizeof(int));
for (i = 0; i < ks; i++) {
if (key[i] != 'j')
dicty[key[i] - 97] = 2;
}
dicty['j' - 97] = 1;
i = 0;
j = 0;
for (k = 0; k < ks; k++) {
if (dicty[key[k] - 97] == 2) {
dicty[key[k] - 97] -= 1;
keyT[i][j] = key[k];
j++;
if (j == 5) {
i++;
j = 0;
}}}
for (k = 0; k < 26; k++) {
if (dicty[k] == 0) {
keyT[i][j] = (char)(k + 97);
j++;
if (j == 5) {
i++;
j = 0;
}}}}
void search(char keyT[5][5], char a, char b, int arr[]) {
int i, j;
if (a == 'j')
a = 'i';
else if (b == 'j')
b = 'i';
for (i = 0; i < 5; i++) {
for (j = 0; j < 5; j++) {
if (keyT[i][j] == a) {
arr[0] = i;
arr[1] = j;
}
else if (keyT[i][j] == b) {
arr[2] = i;
arr[3] = j;
}}}}
int mod5(int a) {
return (a % 5);
}
int prepare(char str[], int ptrs) {
if (ptrs % 2 != 0) {
str[ptrs++] = 'z';
str[ptrs] = '\0';
}
return ptrs;
}
void encrypt(char str[], char keyT[5][5], int ps) {
int i, a[4];
gets(key);
printf("Plain text = ");
gets(str);
encryptByPlayfairCipher(str, key);
printf("Cipher text: %s\n", str);
return 0;
}
b)Decryption
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 30
void toLowerCase(char plain[], int ps)
{
int i;
for (i = 0; i < ps; i++) {
if (plain[i] > 64 && plain[i] < 91)
plain[i] += 32;
}}
int removeSpaces(char* plain, int ps)
{
int i, count = 0;
for (i = 0; i < ps; i++)
if (plain[i] != ' ')
plain[count++] = plain[i];
plain[count] = '\0';
return count;
}
void generateKeyTable(char key[], int ks, char keyT[5][5]) {
else if (b == 'j')
b = 'i';
for (i = 0; i < 5; i++) {
for (j = 0; j < 5; j++) {
if (keyT[i][j] == a) {
arr[0] = i;
arr[1] = j;
}
else if (keyT[i][j] == b) {
arr[2] = i;
arr[3] = j;
}}}}
int mod5(int a)
{
return (a % 5);
}
void decrypt(char str[], char keyT[5][5], int ps) {
int i, a[4];
for (i = 0; i < ps; i += 2) {
search(keyT, str[i], str[i + 1], a);
if (a[0] == a[2]) {
str[i] = keyT[a[0]][mod5(a[1] - 1)];
str[i + 1] = keyT[a[0]][mod5(a[3] - 1)];
}
else if (a[1] == a[3]) {
str[i] = keyT[mod5(a[0] - 1)][a[1]];
str[i + 1] = keyT[mod5(a[2] - 1)][a[1]];
}
else {
str[i] = keyT[a[0]][a[3]];
str[i + 1] = keyT[a[2]][a[1]];
}}}
void decryptByPlayfairCipher(char str[], char key[])
{
char ps, ks, keyT[5][5];
ks = strlen(key);
ks = removeSpaces(key, ks);
toLowerCase(key, ks);
ps = strlen(str);
toLowerCase(str, ps);
ps = removeSpaces(str, ps);
generateKeyTable(key, ks, keyT);
decrypt(str, keyT, ps);
}
int main()
{
char str[20], key[20];
printf("Key text = ");
gets(key);
printf("Cipher text = ");
gets(str);
decryptByPlayfairCipher(str, key);
printf("Deciphered text: %s\n", str);
return 0;
}
RESULTS:
a)Encryption
b)Decryption
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
if(plain[l]!='\0')
{
if(plain[l]==' ')
l++;
p[i][j]=plain[l];
l++;
}
else
{ break; }
}}
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("%c ",p[i][j]);
}
printf("\n");
}
rowtrans(p);
getch();
}
void rowtrans(char p[10][10]){
int l=0,k[10],u;
char c[10][10],x[10][10];
printf("Enter the key to arrange 1 to %d column =\n",col);
for(i=0;i<col;i++)
scanf("%d",&k[i]);
printf("\n**********Encryption**********\n");
for(i=0;i<row;i++)
{ l=0;
for(j=0;j<col;j++)
{
u=k[l]-1;
c[i][j]=p[i][u];
l++;
}
}
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("%c ",c[i][j]);
}
printf("\n");
}
printf("Cipher Text = ");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("%c",c[i][j]);
}}
printf("\n**********Decryption**********\n");
l=0;
for(i=0;i<row;i++)
{ l=0;
for(j=0;j<col;j++)
{
u=k[l]-1;
x[i][u]=c[i][j];
l++;
}}
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("%c ",x[i][j]);
}
printf("\n");
}
printf("Plain Text = ");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("%c",x[i][j]);
}
}
}
RESULTS:
Encryption and Decryption
CONCLUSION:
In this experiment, we have studied about the various Ciphering techniques like Caesar Cipher,
Monoalphabetic Cipher, Playfair Cipher, Transposition Cipher. In different techniques we have
different type keys which produce different cipher texts which can be decrypted and get correct
message only if we know the exact key.
RSA ALGORITHM
AIM: Write a C Program to implement RSA Algorithm for Modern cipher method.
THEORY:
RSA is an algorithm for public-key cryptography that is based on the presumed difficulty of
factoring large integers (the factoring problem). RSA stands for Ron Rivest, Adi Shamir and
Leonard Adleman, who first publicly described it in 1978. A user of RSA creates and then
publishes the product of two large prime numbers, along with an auxiliary value, as their
public key. The prime factors must be kept secret. Anyone can use the public key to encrypt a
message, but with currently published methods, if the public key is large enough, only
someone with knowledge of the prime factors can feasibly decode the message. Whether
breaking RSA encryption is as hard as factoring is an open question known as the RSA
problem.
Method:
The RSA method is based on some principles from number theory. We will now summarize
how to use the method.
With these parameters computed in advance, we are ready to begin encryption. Divide the
plaintext (regarded as a bit string) into blocks, so that each plaintext message, P, falls in the
interval 0 ≤ P < n. Do that by grouping the plaintext into blocks of k bits, where k is the largest
integer for which 2k < n is true.
To encrypt a message, P, compute C = Pe (mod n). To decrypt C, compute P = Cd (mod n). It can
be proven that for all P in the specified range, the encryption and decryption functions are
inverses. To perform the encryption, you need e and n. To perform the decryption, you need
d and n. Therefore, the public key consists of the pair (e, n), and the private key consists of (d,
n).
Example:
A trivial pedagogical example of how the RSA algorithm works is given in Figure. For this
example we have chosen p = 3 and q = 11, giving n = 33 and z = 20. A suitable value for d is d =
7, since 7 and 20 have no common factors. With these choices, e can be found by solving the
equation 7e = 1 (mod 20), which yields e = 3. The ciphertext, C, for a plaintext message, P, is
given by C = P3 (mod 33). The ciphertext is decrypted by the receiver by making use of the rule
P = C7 (mod 33). The figure shows the encryption of the plaintext ''SUZANNE'' as an example.
Because the primes chosen for this example are so small, P must be less than 33, so each
plaintext block can contain only a single character. The result is a monoalphabetic substitution
cipher. If instead we had chosen p and q = 2 512, we would have n = 21024, so each block could be
up to 1024 bits or 128 eight-bit characters.
C PROGRAM:
#include<stdio.h>
#include<math.h>
int gcd(int a, int h)
{
int temp;
while(1)
{
temp = a%h;
if(temp==0)
return h;
a = h;
h = temp;
}
}
int main()
{
int p,q,i;
double c[20],m11[20];
char m[20],m1[20];
printf("Enter message = ");
gets(m);
printf("Enter prime1 p = ");
scanf("%d",&p);
for(i=0; m[i]!='\0';++i)
{
m11[i]=fmod(pow(c[i],d),n);
m1[i]=m11[i]+64;
}
printf("\ne= %lf",e);
printf("\nd= %lf",d);
printf("\nn= %lf ",n);
printf("\ncipher text = ");
for(i=0; m[i]!='\0';i++)
{
printf("%lf ",c[i]);
}
printf("\ndecoded message text = ");
for(i=0; m[i]!='\0';i++)
{
printf("%c",m1[i]);
}
}
RESULTS:
Encryption and Decryption
CONCLUSION:
In this experiment, we have learnt how to encrypt and decrypt data using RSA algorithm and
implemented it. It’s an efficient algorithm and difficult to decode even if data was tracked. It
has any advantage of different keys at encryption and decryption so we can have public and
private keys.
AIM: Write a C program to translate decimal IP address into 32-bit address. Study and implement
a C program to determine if the IP address is in Class A, B, C, D or E.
THEORY:
IP address
• An IP address serves two principal functions: host or network interface identification and
location addressing.
• Its role has been characterized as follows: "A name indicates what we seek. An address
indicates where it is. A route indicates how to get there."
Address classes
• The first class, designated as Class A, contained all addresses in which the most significant
bit is zero. The network number for this class is given by the next 7 bits, therefore
accommodating 128 networks in total, including the zero network.
• Class B network was a network in which all addresses had the two most-significant bits
set to 1 and 0. For these networks, the network address was given by the next 14 bits of
the address, thus leaving 16 bits for numbering host on the network for a total of 65536
addresses per network.
• Class C was defined with the 3 high-order bits set to 1, 1, and 0 and designating the next
21 bits to number the networks, leaving each network with 256 local addresses.
• The leading bit sequence 111 designated an "escape to extended addressing mode", which
was later subdivided in to Class D (1110) for multicast addressing.
• while Class E is reserved for future use the 1111 block designated.
C PROGRAM:
#include <stdio.h>
int dec2bi(int d)
{
int i;
int a[8]={0,0,0,0,0,0,0,0};
for(i=0;i<8;i++) {
a[i]=d%2;
d=d/2;
}
for(i=7;i>=0;i--)
printf("%d",a[i]);
}
int main()
{
int ip[4],i,j;
{
printf("Class D\n");
printf("Net ID bits = Not Defined\n");
printf("Host ID bits = Not Defined\n");
}
else if(ip[0]<256)
{
printf("Class E\n");
printf("Net ID bits = Not Defined\n");
printf("Host ID bits = Not Defined\n");
}
if(ip[0]<256)
{
printf("Binary IP Address = ");
for(i=0;i<4;i++){
dec2bi(ip[i]);
if(i!=3)
printf(".");
} }
else
printf("IP Address is not valid ");
return 0;
}
RESULTS:
CONCLUSION:
In this experiment we have studied about the ip address and its classes. We have converted the
given decimal ip address to binary ip address and classified into their corresponding classes by
analysing the first byte of the given ip address.
PRACTICAL.: 09 Date:10-04-2021
AIM:
(a). To study different elementary wired network models using NS2 (e.g. CBR over UDP, CBR
over TCP, FTP over TCP).
(b). To design and implement a given network topology using NS2 Tcl coding. Also analyze its
performance.
PROGRAMMING:
Part (a):
Example 1: (CBR over UDP)
Result: (Example 1)
Before 1.0ms
After 1.0ms
Result: (Example 2)
Before 1.0ms
After 1.0ms
Result: (Example 3)
Here we are using FTP Application agent as a traffic generator instead of CBR. The difference
is CBR traffic generator will produce constant bit rate where as FTP traffic generator produces
maximum available bit rate.
We are writing code:
Before 1.0ms
After 1.0ms
Part (b):
Network Topology:
$ns at 4.5 "$ns detach-agent $n0 $tcp ; $ns detach-agent $n3 $sink"
RESULT:
CONCLUSION:
In this experiment we have studied different elementary wired network models using
NS2.Designed and implemented the network topology using NS2 Tcl coding. And Also analyze its
performance using Xming.
AIM: To design and implement dynamic network where the routing adjusts to a link failure for a
given topology using NS2.
NETWORK TOPOLOGY:
In a given topology, node 0 sends data traffic to node 3. The network selects the shortest path
between node 0 and node 3 via node 1 and node 2. During transmission the link between node 1
and 2 is down due to some physical circumstance. All the data traffic gets dropped near node 1.
In order to communicate successfully, a routing of data traffic in a network is needed to make
dynamic. For dynamic network design a Tcl programming using NS2 is done in following section
so that the traffic can reach to its desired destination without loss.
n5
1 Mbps, 10 ms 1 Mbps, 10 ms
n6
n4
1 Mbps, 10 ms
1 Mbps, 10 ms
n0
n3
1 Mbps, 10 ms
1 Mbps, 10 ms
n1 Link Failure
n2
1 Mbps, 10 ms
$ns rtproto DV
proc finish {} {
global ns nam_trace
$ns flush-trace
close $nam_trace
exec nam mini.nam &
exit 0
}
RESULT:
CONCLUSION:
In this experiment we have designed and implemented dynamic network with having link
failure at node 1 and node 2 from time 1 sec to 2 sec. During link failure between node 1 and
node 2 the system is not stopped but it followed another shortest path avoiding the node 1 and
node 2 path. Therefore, dynamic routing is important for safe transfer of packets.
AIM: To design and implement a simple two node wireless network topology using NS2.
NETWORK TOPOLOGY:
Creating a simple wireless scenario:
We are going to simulate a very simple 2-node wireless scenario. The topology consists of two mobile-
nodes, node_(0) and node_(1). The mobile-nodes move about within an area whose boundary is defined
in this example as 500mX500m. The nodes start out initially at two opposite ends of the boundary. Then
they move towards each other in the first half of the simulation and again move away for the second
half. A TCP connection is setup between the two mobile-nodes. Packets are exchanged between the
nodes as they come within hearing range of one another. As they move away, packets start getting
dropped.
A mobile-node consists of network components like Link Layer (LL), Interface Queue (IfQ), MAC layer,
the wireless channel nodes transmit and receive signals from etc. At the beginning of a wireless
simulation, we need to define the type for each of these network components. Additionally, we need to
define other parameters like the type of antenna, the radio-propagation model, the type of ad-hoc
routing protocol used by mobile-nodes etc. See comments in the code below for a brief description of
each variable defined.
#=================================================================
# Define options
#=================================================================
set val(chan) Channel/WirelessChannel ;# channel type
set val(prop) Propagation/TwoRayGround ;# radio-propagation model set
val(ant) Antenna/OmniAntenna ;# Antenna type set val(ll)
LL ;# Link layer type set val(ifq)
Queue/DropTail/PriQueue ;# Interface queue type set val(ifqlen) 50
;# max packet in ifq set val(netif) Phy/WirelessPhy ;#
network interface type set val(mac) Mac/802_11 ;# MAC type
set val(rp) DSDV ;# ad-hoc routing protocol set
val(nn) 2 ;# number of mobile-nodes
Next we go to the main part of the program and start by creating an instance of the simulator,
Next create a topology object that keeps track of movements of mobile-nodes within the topological
boundary.
set topo [new Topography]
We had earlier mentioned that mobile-nodes move within a topology of 500mX500m. We provide the
topography object with x and y co-ordinates of the boundary, (x=500, y=500) :
The topography is broken up into grids and the default value of grid resolution is 1. A diferent value can
be passed as a third parameter to load_flatgrid {} above.
create-god $val(nn)
"God (General Operations Director) is the object that is used to store global information about the state
of the environment, network or nodes that an omniscent observer would have, but that should not be
made known to any participant in the simulation." Currently, God object stores the total number of
mobilenodes and a table of shortest number of hops required to reach from one node to another. The
next hop information is normally loaded into god object from movement pattern files, before simulation
begins, since calculating this on the fly during simulation runs can be quite time consuming.
Next, we create mobile-nodes. First, we need to configure nodes before we can create them. Node
configuration API may consist of defining the type of addressing (flat/hierarchical etc), the type of Ad-
hoc routing protocol, Link Layer, MAC layer, IfQ etc. The configuration API can be defined as follows:
(parameter examples)
# $ns_ node-config -addressingType flat or hierarchical or expanded
All default values for these options are NULL except: addressingType: flat
We are going to use the default value of flat addressing; also let’s turn on only AgentTrace and
RouterTrace; you can experiment with the traces by turning all of them on. AgentTraces are marked
with AGT, RouterTrace with RTR and MacTrace with MAC in their 5th fields. MovementTrace, when
turned on, shows the movement of the mobile-nodes and the trace is marked with M in their 2nd field.
# Configure nodes
$ns_ node-config -adhocRouting $val(rp) \
-llType $val(ll) \
-macType $val(mac) \
-ifqType $val(ifq) \
-ifqLen $val(ifqlen) \
-antType $val(ant) \
-propType $val(prop) \
-phyType $val(netif) \
-topoInstance $topo \
-channelType $val(chan) \
-agentTrace ON \
-routerTrace ON \
-macTrace OFF \
-movementTrace OFF
Now that we have created mobile-nodes, we need to give them a position to start with,
#
# Provide initial (X,Y, for now Z=0) co-ordinates for node_(0) and node_(1) #
$node_(0) set X_ 5.0
$node_(0) set Y_ 2.0
$node_(0) set Z_ 0.0
#
# Node_(1) starts to move towards node_(0) #
$ns_ at 50.0 "$node_(1) setdest 25.0 20.0 15.0"
$ns_ at 10.0 "$node_(0) setdest 20.0 18.0 1.0"
$ns_ at 50.0 "$node_(1) setdest 25.0 20.0 15.0" means at time 50.0s, node1 starts to move towards the
destination (x=25,y=20) at a speed of 15m/s. This API is used to change direction and speed of
movement of the mobile-nodes.
This sets up a TCP connection between the two nodes with a TCP source on node0.
Then we need to define stop time when the simulation ends and tell mobile-nodes to reset which
actually resets their internal network components,
#
# Tell nodes when the simulation ends
#
for {set i 0} {$i < $val(nn) } {incr i} {
$ns_ at 150.0 "$node_($i) reset";
}
$ns_ at 150.0001 "stop"
$ns_ at 150.0002 "puts \"NS EXITING...\" ; $ns_ halt" proc stop
{} { global ns_ tracefd close $tracefd }
At time 150.0s, the simulation shall stop. The nodes are reset at that time and the "$ns_ halt" is called at
150.0002s, a little later after resetting the nodes. The procedure stop{} is called to flush out traces and
close the trace file. And finally the command to start the simulation,
#Setup Trace
set tracefd [open prac11.tr w]
$ns trace-all $tracefd
#Setup Nam
set namfile [open prac11.nam w]
$ns namtrace-all-wireless $namfile 500 500
#Configuring mobilenodes
$ns node-config -adhocRouting $val(rp) \
-llType $val(ll) \
-macType $val(mac) \
-ifqType $val(ifq) \
-ifqLen $val(ifqlen) \
-antType $val(ant) \
-propType $val(prop) \
-phyType $val(netif) \
-topoInstance $topo \
-channelType $val(chan) \
-agentTrace ON \
-routerTrace ON \
-macTrace OFF \
-movementTrace OFF
#node1 at (390,385,0)
$node(1) set X_ 390.0
$node(1) set Y_ 385.0
$node(1) set Z_ 0.0
$ns initial_node_pos $node(1) 20
RESULT:
(i) Start
(iii) FTP
(vi) Stop
CONCLUSION:
In this experiment we have designed and implemented simple two nodes wireless network
topology. The nodes start out initially at two opposite ends of the boundary. Then they move
towards each other in the first half of the simulation and again move away for the second half.