You are on page 1of 101

SARDAR VALLABHBHAI NATIONAL INSTITUTE OF

TECHNOLOGY
ICHCHANATH, PIPLOD, SURAT-395007

LABORATORY MANUAL

ELECTRONICS ENGINEERING DEPARTMENT

EC: 302: DATA COMMUNICATION & NETWORKING

B. TECH III-SEMESTER VI

NAME: MALOTH BHARATH BABU

ROLL NO: U18EC096

BATCH: A3
SARDAR VALLABHBHAI NATIONAL INSTITUTE OF
TECHNOLOGY
ICHCHANATH, PIPLOD, SURAT-395007

ELECTRONICS ENGINEERING DEPARTMENT

CERTIFICATE

This is to certify that Ms./Mr. MALOTH BHARATH BABU________


Roll no. U18EC096 has satisfactorily completed the lab exercises for

EC: 302: DATA COMMUNICATION & NETWORKING of B. TECH III- SEMESTER VI

in the academic Year 2020-2021

SUBJECT CO-ORDINATOR

DATE: 28-04-2021
INDEX
SI
SR. PAGE
DATE PRACTICAL NAME G
NO. NO.
N

TCP/IP PROTOCOL STACK AND SOME NETWORK


13-01-2021 1-14
1. MANAGEMENT COMMANDS

CYCLIC REDUNDENCY CHECK (CRC) METHOD FOR ERROR


2. DETECTION 15-21
20-01-2021

HAMMING CODE FOR ERROR DETECTION & CORRECTION 22-26


3. 03-02-2021

BIT STUFFING & DE-STUFFING 27-32


4. 10-02-2021

SHORTEST PATH ALGORITHM 33-37


5. 17-02-2021

CIPHERING TECHNIQUES 38-58


6. 11-03-2021

RSA ALGORITHM 59-63


7. 24-03-2021

IP ADDRESS AND ITS CLASSES 64-68


8. 24-03-2021

ELEMENTARY NETWORK MODEL DESIGN USING NS2 69-79


9. 10-04-2021

NETWORK DYNAMICS USING NS2 80-85


10. 20-04-2021

WIRELESS NETWORK DESIGN USING NS2 86-96


11.. 27-04-2021
EC:302 DCN 2021

PRACTICAL NO.: 1 Date:13-01-2021

TCP/IP PROTOCOL STACK AND


SOME NETWORK MANAGEMENT COMMANDS

AIM: To study TCP/IP protocol stack and some network management commands like IPCONFIG,
PING and TRACERT.

TCP/IP PROTOCOL STACK:


It stands for Transmission Control Protocol/Internet Protocol. It is the basis of internet and
widely used on corporate LANs. Protocol stack is a set of protocol layers that work together.
The TCP/IP protocol model organizes the communication task into five relatively independent
layers. 1. Physical layer

2. Data Link Layer


3. Network layer
4. Host-to-Host or Transport layer
5. Application layer.
It is as shown in the figure.

Application
L ayer

Transport L ayer

Network L ayer

Data link L ayer


Frame IP TCP/UDP Frame
Header Header Header Data Trailer

P h ysical Layer

Network Frame

Figure 1: TCP/IP Protocol Stack

S.V.N.I.T, SURAT Page 1


EC:302 DCN 2021

TCP/IP NETWORK MANAGEMENT COMMANDS:


1. IPCONFIG:
It displays all current TCP/IP network configuration values and refreshes Dynamic Host
Configuration Protocol (DHCP) and Domain Name System (DNS) settings. Used without
parameters, ipconfig displays the IP address, subnet mask, and default gateway for all adapters.

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.

ipconfig without parameters.

/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.

S.V.N.I.T, SURAT Page 2


EC:302 DCN 2021

/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.

/?: Displays help at the command prompt.

EXAMPLES:
To display the basic TCP/IP configuration for all adapters, type:
ipconfig

To display the full TCP/IP configuration for all adapters, type:


ipconfig /all

To renew a DHCP-assigned IP address configuration for only the Local Area Connection adapter,
type:

ipconfig /renew "Local Area Connection"

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*

S.V.N.I.T, SURAT Page 3


EC:302 DCN 2021

To set the DHCP class ID for the Local Area Connection adapter to TEST, type:
ipconfig /setclassid "Local Area Connection" TEST

2. PING:

It verifies IP-level connectivity to another TCP/IP computer by sending Internet Control


Message Protocol (ICMP) Echo Request messages. The receipt of corresponding Echo Reply
messages are displayed, along with round-trip times. Ping is the primary TCP/IP command used
to troubleshoot connectivity, reachability and name resolution. Used without parameters, ping
displays help.

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.

S.V.N.I.T, SURAT Page 4


EC:302 DCN 2021

-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).

S.V.N.I.T, SURAT Page 5


EC:302 DCN 2021

TargetName: Specifies the destination, which is identified either by IP address or host name.

/? : Displays help at the command prompt.

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

S.V.N.I.T, SURAT Page 6


EC:302 DCN 2021

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).

TargetName : Specifies the destination, identified either by IP address or host name.

/? : Displays help at the command prompt.

EXAMPLES:

To trace the path to the host named corp7.microsoft.com, type:


tracert corp7.microsoft.com

S.V.N.I.T, SURAT Page 7


EC:302 DCN 2021

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

S.V.N.I.T, SURAT Page 8


EC:302 DCN 2021

ipconfig /?

ipconfig /all

S.V.N.I.T, SURAT Page 9


EC:302 DCN 2021

ipconfig /renew

ipconfig /release

S.V.N.I.T, SURAT Page 10


EC:302 DCN 2021

ipconfig /flushdns

ipconfig /displaydns

ping [Target Name]

S.V.N.I.T, SURAT Page 11


EC:302 DCN 2021

ping –t [Target Name]

ping –n [count] [Target Name]

ping –l [size] [Target Name]

S.V.N.I.T, SURAT Page 12


EC:302 DCN 2021

ping –i [TTL] [Target Name]

Ping 127.0.0.1

tracert [Target Name]

S.V.N.I.T, SURAT Page 13


EC:302 DCN 2021

tracert -d [Target Name]

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.

Signature of the Teacher

S.V.N.I.T, SURAT Page 14


EC:302 DCN 2021

PRACTICAL NO.: 2 DATE :20.01.2021

CYCLIC REDUNDENCY CHECK (CRC) METHOD FOR ERROR DETECTION

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 1: MODULO-2 EQUATION 1: THE CRC-16


CALCULATION POLYNOMIAL

S.V.N.I.T, SURAT Page 15


EC:302 DCN 2021

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

2. The reverse calculation is shown in Example 3.

EXAMPLE 2: CALCULATION FOR GENERATING CRC

EXAMPLE 3: CHECKING A MESSAGE FOR A CRC ERROR

FLOW CHART:

S.V.N.I.T, SURAT Page 16


EC:302 DCN 2021

C PROGRAM:
(i) Encoder Side
/*ENCODING THE GIVEN DATA*/

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

S.V.N.I.T, SURAT Page 17


EC:302 DCN 2021

int rem(int,int);

void main()
{
int i,j,d_len,div_len;
int data[10],divs[5],data1[15],crc[5],edata[15];

printf("\n Enter the Data Length= ");


scanf("%d",&d_len);
printf("\n Enter the Divisor Length= ");
scanf("%d",&div_len);
printf("\n Enter the Data : ");
for(i=0;i<d_len;i++)
scanf("%d",&data[i]);
printf("\n Enter the Divisor : ");
for(i=0;i<div_len;i++)
scanf("%d",&divs[i]);
printf("\n The New Data is : ");
for(i=0;i<(d_len+div_len-1);i++)
{
if(i<d_len)
data1[i]=data[i];
else
data1[i]=0;
printf("%d",data1[i]);
}
for(j=0;j<=d_len;j++)
{
for(i=0;i<div_len;i++)
{
crc[i]=data1[i+j];
if(crc[0]==1)
data1[i+j]=rem(data1[i+j],divs[i]);
else
data1[i+j]=rem(data1[i+j],0);
}

S.V.N.I.T, SURAT Page 18


EC:302 DCN 2021

printf("\n The CRC is : ");


for(i=0;i<div_len-1;i++)
printf("%d",crc[i]);

printf("\n The DATA to be send is : ");


for(i=0;i<(d_len+div_len-1);i++)
{
if(i<d_len)
edata[i]=data[i];
else
edata[i]=crc[i-d_len];
printf("%d",edata[i]);
}

getch();
}

int rem(int x, int y)


{
if(x==y)
return 0;
else
return 1;
}

(ii) Decoder Side


/*DECODING THE GIVEN DATA*/

#include<stdio.h>
#include<conio.h>
int rem(int,int);

void main()

S.V.N.I.T, SURAT Page 19


EC:302 DCN 2021

{
int i,j,k,d_len,div_len;
int divs[5],recdata[15],remd[5];

printf("\n Enter the Data Length= ");


scanf("%d",&d_len);
printf("\n Enter the Divisor Length= ");
scanf("%d",&div_len);
printf("\n Enter the Divisor : ");
for(i=0;i<div_len;i++)
scanf("%d",&divs[i]);
printf("\n Enter the Receiver side data : ");
for(i=0;i<(d_len+div_len-1);i++)
scanf("%d",&recdata[i]);
for(j=0;j<=d_len;j++)
{
for(i=0;i<div_len;i++)
{
remd[i]=recdata[i+j];
if(remd[0]==1)
recdata[i+j]=rem(recdata[i+j],divs[i]);
else
recdata[i+j]=rem(recdata[i+j],0);
}
}
printf("\n The Reminder is : ");
k=0;
for(i=0;i<div_len-1;i++)
{
printf("%d",remd[i]);
if(remd[i]==0)
k++;
}
if(k==div_len-1)
printf("\n ||<THERE IS NO ERROR>||");
else
printf("\n ||<THERE IS AN ERROR>||");
getch();
}

S.V.N.I.T, SURAT Page 20


EC:302 DCN 2021

int rem(int x, int y)


{
if(x==y)
return 0;
else
return 1;
}

RESULTS:
(i) Encoder Side

(ii) Decoder 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.

S.V.N.I.T, SURAT Page 21


EC:302 DCN 2021

Signature of the Teacher

PRACTICAL NO.: 3 Date: 03-02-2021

HAMMING CODE FOR ERROR DETECTION & CORRECTION

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.

Calculating the Hamming Code:


The key to the Hamming Code is the use of extra parity bits to allow the identification of a
single error. Create the code word as follows:

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,……………)

S.V.N.I.T, SURAT Page 22


EC:302 DCN 2021

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-

127, 160-191,…………….) etc.

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

Position 2 checks bits 2, 3, 6, 7, 10, 11: 0 ? 1 _ 0 0 1 _ 1 0 1 0. Odd parity so set position 2


to a 1: 0 1 1 _ 0 0 1 _ 1 0 1 0
Position 4 checks bits 4, 5, 6, 7, 12: 0 1 1 ? 0 0 1 _ 1 0 1 0. Odd parity so set position
4 to a 1: 0 1 1 1 0 0 1 _ 1 0 1 0
Position 8 checks bits 8, 9, 10, 11, 12: 0 1 1 1 0 0 1 ? 1 0 1 0. Even parity so set position 8

to a 0: 0 1 1 1 0 0 1 0 1 0 1 0 Code word: 011100101010.

Finding and fixing a bad bit:


The above example created a code word of 011100101010. Suppose the word that was
received was 011100101110 instead. Then the receiver could calculate which bit was wrong

S.V.N.I.T, SURAT Page 23


EC:302 DCN 2021

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

S.V.N.I.T, SURAT Page 24


EC:302 DCN 2021

S.V.N.I.T, SURAT Page 25


EC:302 DCN 2021

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("Encoded data is = ");


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

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 {

S.V.N.I.T, SURAT Page 26


EC:302 DCN 2021

printf("\nError position = %d",c);


rdata[7-c]=1^rdata[7-c];
printf("\nCorrected data = ");
for(i=0;i<7;i++)
printf("%d",rdata[i]);
}
}

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.

Signature of the Teacher

S.V.N.I.T, SURAT Page 27


EC:302 DCN 2021

- PRACTICAL NO.: 4 Date:10-02-2021

BIT STUFFING & DE-STUFFING


AIM: Write a C Program to implement Bit Stuffing and De-stuffing method for Bit Oriented
Protocols.

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

S.V.N.I.T, SURAT Page 28


EC:302 DCN 2021

11111011111011011111101011111010

FLAG FLAG

Bit Inverted

FLAG FLAG FLAG

(a) An inverted bits splits a frame in two

FLAG FLAG FLAG

Bit Inverted

FLAG FLAG

(b) An inverted bit merges two frames

S.V.N.I.T, SURAT Page 29


EC:302 DCN 2021

Flow Chart: -

S.V.N.I.T, SURAT Page 30


EC:302 DCN 2021

S.V.N.I.T, SURAT Page 31


EC:302 DCN 2021

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]);

S.V.N.I.T, SURAT Page 32


EC:302 DCN 2021

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

S.V.N.I.T, SURAT Page 33


EC:302 DCN 2021

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.

Signature of the Teacher

S.V.N.I.T, SURAT Page 34


EC:302 DCN 2021

PRACTICAL NO.: 5 Date: 17-02-2021

SHORTEST PATH ALGORITHM

AIM: Write a C Program to implement Shortest Path Routing Algorithm.

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).

S.V.N.I.T, SURAT Page 35


EC:302 DCN 2021

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:");

S.V.N.I.T, SURAT Page 36


EC:302 DCN 2021

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;

S.V.N.I.T, SURAT Page 37


EC:302 DCN 2021

do{
j=pred[j];
printf("<-%d",j);
}while(j!=startnode);
}

RESULTS:
Input:

Output:
Shortest distance between 5→1

S.V.N.I.T, SURAT Page 38


EC:302 DCN 2021

Input:

Output:
Shortest distance between A(1)→E(5)

Shortest distance between E(5)→A(1)

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.

Signature of the Teacher

S.V.N.I.T, SURAT Page 39


EC:302 DCN 2021

- PRACTICAL NO.: 6 Date:11-03-2021

CIPHERING TECHNIQUES

AIM: Write a C Program to implement Cipher text using classical Cipher method.

THEORY:

A cipher (or cypher) is an algorithm for performing encryption or decryption - a series of


well-defined steps that can be followed as a procedure. An alternative, less common term is
encipherment. When using a cipher, the original information is known as plaintext, and the
encrypted form as cipher text. The cipher text message contains all the information of the
plaintext message, but is not in a format readable by a human or computer without the
proper mechanism to decrypt it; it should resemble random gibberish to those not intended
to read it.
Classical ciphers are often divided into transposition ciphers and substitution ciphers.
Most modern ciphers can be categorized in several ways:
1. By whether they work on blocks of symbols usually of a fixed size (block ciphers), or
on a continuous stream of symbols (stream ciphers).
2. By whether the same key is used for both encryption and decryption (symmetric key
algorithms), or if a different key is used for each (asymmetric key algorithms). If the
algorithm is symmetric, the key must be known to the recipient and sender and to no
one else. If the algorithm is an asymmetric one, the enciphering key is different from,
but closely related to, the deciphering key. If one key cannot be deduced from the
other, the asymmetric key algorithm has the public/private key property and one of
the keys may be made public without loss of confidentiality.

S.V.N.I.T, SURAT Page 40


EC:302 DCN 2021

Ciphers

Classical Rotor Machines Modern

Substitution Transposition Private Key Public Key

Stream Block

Figure 1: Types of Ciphers

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

S.V.N.I.T, SURAT Page 41


EC:302 DCN 2021

The general system of symbol-for-symbol substitution is called a monoalphabetic


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.

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.

Figure 2: Transposition Cipher

S.V.N.I.T, SURAT Page 42


EC:302 DCN 2021

ALGORITHM:
Algorithm for transposition cipher is:

START

Enter the Key

Enter the message

Break the message in different


packets same as that of key size

Check the key & give priority


according to alphabetical order

Type the message under the key, According


to priority of alphabetical order of key. Take
character of that position of each packet.

Combine all character words


& we will get the Cipher text.

Transmit the cipher text

END

S.V.N.I.T, SURAT Page 43


EC:302 DCN 2021

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()
{

S.V.N.I.T, SURAT Page 44


EC:302 DCN 2021

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

S.V.N.I.T, SURAT Page 45


EC:302 DCN 2021

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]);
}
}

S.V.N.I.T, SURAT Page 46


EC:302 DCN 2021

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]);
}
}

S.V.N.I.T, SURAT Page 47


EC:302 DCN 2021

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] != ' ')

S.V.N.I.T, SURAT Page 48


EC:302 DCN 2021

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;

S.V.N.I.T, SURAT Page 49


EC:302 DCN 2021

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

S.V.N.I.T, SURAT Page 50


EC:302 DCN 2021

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 encryptByPlayfairCipher(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);
ps = prepare(str, ps);
generateKeyTable(key, ks, keyT);
encrypt(str, keyT, ps);
}
int main()
{
char str[20], key[20];
printf("Key text = ");

S.V.N.I.T, SURAT Page 51


EC:302 DCN 2021

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]) {

S.V.N.I.T, SURAT Page 52


EC:302 DCN 2021

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';

S.V.N.I.T, SURAT Page 53


EC:302 DCN 2021

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]];

S.V.N.I.T, SURAT Page 54


EC:302 DCN 2021

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

S.V.N.I.T, SURAT Page 55


EC:302 DCN 2021

RESULTS:
a)Encryption

b)Decryption

ROW TRANSPOSITION CIPHER: -


Encryption and Decryption
#include <stdio.h>
#include<conio.h>
#include<string.h>
void rowtrans(char p[10][10]);
void coltrans(char p[10][10]);
int row,col,i,j;
char p[10][10];
void main()
{
int ch=0,l=0;
char plain[100];
printf("Enter the plain text = ");
gets(plain);
printf("Enter no of rows = ");
scanf("%d",&row);
printf("Enter no of columns = ");
scanf("\n%d",&col);

S.V.N.I.T, SURAT Page 56


EC:302 DCN 2021

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++)

S.V.N.I.T, SURAT Page 57


EC:302 DCN 2021

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;

S.V.N.I.T, SURAT Page 58


EC:302 DCN 2021

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]);
}
}
}

S.V.N.I.T, SURAT Page 59


EC:302 DCN 2021

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.

Signature of the Teacher

S.V.N.I.T, SURAT Page 60


EC:302 DCN 2021

PRACTICAL NO.: 7 Date:24-03-2021

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.

1. Choose two large primes, p and q (typically 1024 bits).


2. Compute n = p x q and z = (p - 1) x (q - 1).
3. Choose a number relatively prime to z and call it d.
4. Find e such that e x d = 1 mod z.

S.V.N.I.T, SURAT Page 61


EC:302 DCN 2021

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.

S.V.N.I.T, SURAT Page 62


EC:302 DCN 2021

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);

S.V.N.I.T, SURAT Page 63


EC:302 DCN 2021

printf("Enter prime2 q = ");


scanf("%d",&q);
double n=p*q;
double phi=(p-1)*(q-1);
double e=2;
while (e < phi)
{
if (gcd(e, phi)==1)
break;
else
e++;
}
int k=1;
double d=(1+(k*phi))/e;
for(i=0; m[i]!='\0';i++)
{
c[i]=m[i]-64;
c[i]=pow(c[i],e);
c[i]=fmod(c[i],n);
}

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 = ");

S.V.N.I.T, SURAT Page 64


EC:302 DCN 2021

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.

Signature of the Teacher

S.V.N.I.T, SURAT Page 65


EC:302 DCN 2021

- PRACTICAL NO.: 8 Date:24-03-2021

IP ADDRESS AND ITS CLASSES

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.

Range : 0.0.0.0 to 127.255.255.255

• 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.

Range : 128.0.0.0 to 191.255.255.255

• 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.

Range : 192.0.0.0 to 223.255.255.255

S.V.N.I.T, SURAT Page 66


EC:302 DCN 2021

• The leading bit sequence 111 designated an "escape to extended addressing mode", which
was later subdivided in to Class D (1110) for multicast addressing.

Range : 224.0.0.0 to 239.255.255.255

• while Class E is reserved for future use the 1111 block designated.

Range : 240.0.0.0 to 255.255.255.255

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]);
}

S.V.N.I.T, SURAT Page 67


EC:302 DCN 2021

int main()
{
int ip[4],i,j;

printf("Enter Decimal IP Address in array form = ");


for(i=0;i<4;i++)
scanf("%d",&ip[i]);
printf("Decimal IP Address = ");
for(i=0;i<4;i++)
{
printf("%d",ip[i]);
if(i!=3)
printf(".");
}
printf("\n");
if(ip[0]<128)
{
printf("Class A\n");
printf("Net ID bits = %d",ip[0]);
printf("\nHost ID bits = %d.%d.%d\n",ip[1],ip[2],ip[3]);
}
else if(ip[0]<192)
{
printf("Class B\n");
printf("Net ID bits = %d.%d",ip[0],ip[1]);
printf("\nHost ID bits = %d.%d\n",ip[2],ip[3]);
}
else if(ip[0]<224)
{
printf("Class C\n");
printf("Net ID bits = %d.%d.%d",ip[0],ip[1],ip[2]);
printf("\nHost ID bits = %d\n",ip[3]);
}
else if(ip[0]<240)

S.V.N.I.T, SURAT Page 68


EC:302 DCN 2021

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

S.V.N.I.T, SURAT Page 69


EC:302 DCN 2021

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.

Signature of the Teacher

S.V.N.I.T, SURAT Page 70


EC:302 DCN 2021

PRACTICAL.: 09 Date:10-04-2021

ELEMENTARY NETWORK MODEL DESIGN USING NS2

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)

set ns [new Simulator] Creating ns simulator object


set tracefile [open out.tr w]
Open trace file (Optional)
$ns trace-all $tracefile
set nf [open out.nam w]
Open the nam trace file
$ns namtrace-all $nf
proc finish {} {
global ns tracefile nf
$ns flush-
trace close
'finish' procedure
$nf
close $tracefile
exec nam out.nam
& exit 0
}
set n0 [$ns node] set n1 [$ns node] Create your topology
$ns simplex-link $n0 $n1 1Mb 10ms DropTail - set n0 nodes….
- $ns simplex/duplex-links…

S.V.N.I.T, SURAT Page 71


EC:302 DCN 2021

set udp0 [new Agent/UDP]


$ns attach-agent $n0 $udp0
set cbr[new Application/Traffic/CBR] Create your agents
$cbr attach-agent $udp0 set null0 [new -transport layer and application layers
Agent/Null] stuff
$ns attach-agent $n1 $null0
$ns connect $udp0 $null0
$ns at 1.0 "$cbr start" Scheduling Events
$ns at 3.0 "finish" - $ns at 1.0 start and at 3.0 finish

$ns run starts the simulation.

Result: (Example 1)

Before 1.0ms

S.V.N.I.T, SURAT Page 72


EC:302 DCN 2021

After 1.0ms

S.V.N.I.T, SURAT Page 73


EC:302 DCN 2021

Example 2: (CBR over TCP)

set ns [new Simulator] Creating ns simulator object


set tracefile [open out.tr w]
Open trace file (Optional)
$ns trace-all $tracefile
set nf [open out.nam w]
Open the nam trace file
$ns namtrace-all $nf
proc finish {} {
global ns tracefile nf
$ns flush-trace
close $nf
'finish' procedure
close $tracefile
exec nam out.nam &
exit 0
}
set n0 [$ns node] set Create your topology
n1 [$ns node] - set n0 nodes….
$ns simplex-link $n0 $n1 1Mb 10ms DropTail - $ns duplex-links…
set tcp0 [new Agent/TCP]
$ns attach-agent $n0 $tcp0
set cbr0 [new Application/Traffic/CBR] Create your agents
$cbr0 attach-agent $tcp0 -transport layer and application layers
set tcpsink0 [new Agent/TCPSink] stuff
$ns attach-agent $n1 $tcpsink0
$ns connect $tcp0 $tcpsink0
Scheduling Events
$ns at 1.0 "$cbr start"
$ns at 3.0 "finish" - $ns at 1.0 start
and at 3.0 finish
$ns run Starts the simulation.

Note: Source obtained from http://csis.bits-pilani.ac.in/faculty/murali/resources/tutorials/ns2.htm

S.V.N.I.T, SURAT Page 74


EC:302 DCN 2021

Result: (Example 2)

Before 1.0ms

After 1.0ms

S.V.N.I.T, SURAT Page 75


EC:302 DCN 2021

Example 3: (FTP over TCP)

set ns [new Simulator] Creating ns simulator object


set tracefile [open out.tr w]
Open trace file (Optional)
$ns trace-all $tracefile
set nf [open out.nam w]
Open the nam trace file
$ns namtrace-all $nf
proc finish {} {
global ns tracefile nf
$ns flush-
trace close $nf
'finish' procedure
close $tracefile
exec nam out.nam
& exit 0
}
set n0 [$ns node] Create your topology
set n1 [$ns node] - set n0 nodes….
$ns simplex-link $n0 $n1 1Mb 10ms DropTail - $ns duplex-links…
set tcp0 [new Agent/TCP]
$ns attach-agent $n0 $tcp0
set ftp0 [new Application/FTP] Create your agents
$ftp0 attach-agent $tcp0 -transport layer and application layers
set tcpsink0 [new Agent/TCPSink] stuff
$ns attach-agent $n1 $tcpsink0
$ns connect $tcp0 $tcpsink0
Scheduling Events
$ns at 1.0 "$ftp0 start"
$ns at 3.0 "finish" - $ns at 1.0
start and at 3.0
finish
$ns run starts the simulation.

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:

S.V.N.I.T, SURAT Page 76


EC:302 DCN 2021

set ftp0 [new Application/FTP]


$ftp0 attach-agent $tcp0
and Similarly for telnet
also
set telneto [new Application/TELNET]
$ftp0 attach-agent
$telnet0 Instead of CBR
set cbr0 [new Application/Traffic/CBR]
$cbr0 attach-agent $tcp0

Before 1.0ms

S.V.N.I.T, SURAT Page 77


EC:302 DCN 2021

After 1.0ms

Part (b):
Network Topology:

S.V.N.I.T, SURAT Page 78


EC:302 DCN 2021

NS-2 Programming (Tcl Script):

# Create a simulator object


set ns [new Simulator]

# Define different colors


# for data flows (for NAM)
$ns color 1 Blue
$ns color 2 Red

# Open the NAM trace file


set nf [open aout.nam w]
$ns namtrace-all $nf

# Define a 'finish' procedure


proc finish {} {
global ns nf
$ns flush-trace

# Close the NAM trace file


close $nf

# Execute NAM on the trace file


exec nam out.nam &
exit 0
}

# Create four nodes


set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]

# Create links between the nodes


$ns duplex-link $n0 $n2 2Mb 10ms DropTail
$ns duplex-link $n1 $n2 2Mb 10ms DropTail
$ns duplex-link $n2 $n3 1.7Mb 20ms DropTail

# Set Queue Size of link (n2-n3) to 10


$ns queue-limit $n2 $n3 10

# Give node position (for NAM)


$ns duplex-link-op $n0 $n2 orient right-down
$ns duplex-link-op $n1 $n2 orient right-up
$ns duplex-link-op $n2 $n3 orient right

S.V.N.I.T, SURAT Page 79


EC:302 DCN 2021

# Monitor the queue for link (n2-n3). (for NAM)


$ns duplex-link-op $n2 $n3 queuePos 0.5

# Setup a TCP connection


set tcp [new Agent/TCP]
$tcp set class_ 2
$ns attach-agent $n0 $tcp

set sink [new Agent/TCPSink]


$ns attach-agent $n3 $sink
$ns connect $tcp $sink
$tcp set fid_ 1

# Setup a FTP over TCP connection


set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ftp set type_ FTP

# Setup a UDP connection


set udp [new Agent/UDP]
$ns attach-agent $n1 $udp
set null [new Agent/Null]

$ns attach-agent $n3 $null


$ns connect $udp $null
$udp set fid_ 2

# Setup a CBR over UDP connection


set cbr [new Application/Traffic/CBR]
$cbr attach-agent $udp
$cbr set type_ CBR
$cbr set packet_size_ 1000
$cbr set rate_ 1mb
$cbr set random_ false

# Schedule events for the CBR and FTP agents


$ns at 0.1 "$cbr start"
$ns at 1.0 "$ftp start"
$ns at 4.0 "$ftp stop"
$ns at 4.5 "$cbr stop"

# Detach tcp and sink agents


# (not really necessary)

S.V.N.I.T, SURAT Page 80


EC:302 DCN 2021

$ns at 4.5 "$ns detach-agent $n0 $tcp ; $ns detach-agent $n3 $sink"

# Call the finish procedure after


# 5 seconds of simulation time
$ns at 5.0 "finish"

# Print CBR packet size and interval


puts "CBR packet size = [$cbr set packet_size_]"
puts "CBR interval = [$cbr set interval_]"

# Run the simulation


$ns run

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.

Signature of the Teacher

S.V.N.I.T, SURAT Page 81


EC:302 DCN 2021

PRACTICAL NO.: 10 Date:20-04-2021

NETWORK DYNAMICS USING NS2

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

Note: Source obtained from http://www.isi.edu/nsnam/ns/tutorial/

S.V.N.I.T, SURAT Page 82


EC:302 DCN 2021

NS-2 Programming (Tcl Script):


# Create a simulator object
set ns [new Simulator]

$ns rtproto DV

# Data flows colors


$ns color 1 dodgerblue

# Open the NAM trace file


set nam_trace [open mini.nam w]
$ns namtrace-all $nam_trace

proc finish {} {
global ns nam_trace
$ns flush-trace
close $nam_trace
exec nam mini.nam &
exit 0
}

#Create seven nodes


for {set i 0} {$i < 7} {incr i} {
set n($i) [$ns node]}

# Create links between the nodes


for {set i 0} {$i < 7} {incr i} {
$ns duplex-link $n($i) $n([expr ($i+1)%7]) 1Mb 10ms DropTail}

S.V.N.I.T, SURAT Page 83


EC:302 DCN 2021

# Setup a UDP connection b/w n1 and n2


set udp [new Agent/UDP]
$ns attach-agent $n(0) $udp
# Setup a CBR over UDP connection
set cbr [new Application/Traffic/CBR]
$cbr attach-agent $udp
$cbr set type_ CBR
$cbr set packet_size_ 500
$cbr set interval_ 0.005
$cbr set random_ false
#Setup a null at n3 node
set null [new Agent/Null]
$ns attach-agent $n(3) $null
$ns connect $udp $null
$udp set fid_ 1

# Schedule events for the CBR and FTP agents


$ns at 0.1 "$cbr start"
#Link Falure b/1 n1 and n2 1.0 to 2.0 seconds
$ns rtmodel-at 1.0 down $n(1) $n(2)
#Link up after 2.0
$ns rtmodel-at 2.0 up $n(1) $n(2)
$ns at 4.5 "$cbr stop"

$ns at 5.0 "finish"

# Run the simulation


$ns run

S.V.N.I.T, SURAT Page 84


EC:302 DCN 2021

RESULT:

Figure 1: Before Link Failure between node 1 and node 2

Figure 2: Links Fails between node 1 and node 2

S.V.N.I.T, SURAT Page 85


EC:302 DCN 2021

Figure 3: After Link Failure between node 1 and node 2

Figure 4: After link upgrades between node 1 and node 2

S.V.N.I.T, SURAT Page 86


EC:302 DCN 2021

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.

Signature of the Teacher

S.V.N.I.T, SURAT Page 87


EC:302 DCN 2021

PRACTICAL NO.: 11 Date: 27-04-2021

WIRELESS NETWORK DESIGN USING NS2

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,

S.V.N.I.T, SURAT Page 88


EC:302 DCN 2021

set ns_ [new Simulator]


Then setup trace support by opening file simple.tr and call the procedure trace-all {} as follows:

set tracefd [open simple.tr w] $ns_


trace-all $tracefd

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

$topo load_flatgrid 500 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.

Next we create the object God, as follows:

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

S.V.N.I.T, SURAT Page 89


EC:302 DCN 2021

# -adhocRouting DSDV or DSR or TORA


# -llType LL
# -macType Mac/802_11
# -propType "Propagation/TwoRayGround"
# -ifqType "Queue/DropTail/PriQueue"
# -ifqLen 50
# -phyType "Phy/WirelessPhy"
# -antType "Antenna/OmniAntenna"
# -channelType "Channel/WirelessChannel"
# -topoInstance $topo
# -energyModel "EnergyModel"
# -initialEnergy (in Joules)
# -rxPower (in W)
# -txPower (in W)
# -agentTrace ON or OFF
# -routerTrace ON or OFF
# -macTrace ON or OFF
# -movementTrace ON or OFF

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.

The configuration API for creating mobile-nodes looks as follows:

# 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) \

S.V.N.I.T, SURAT Page 90


EC:302 DCN 2021

-phyType $val(netif) \
-topoInstance $topo \
-channelType $val(chan) \
-agentTrace ON \
-routerTrace ON \
-macTrace OFF \
-movementTrace OFF

Next we create the 2 mobile-nodes as follows:

for {set i 0} {$i < $val(nn) } {incr i} {


set node_($i) [$ns_ node ]
$node_($i) random-motion 0 ;# disable random motion
}
The random-motion for nodes is disabled here, as we are going to provide node position and movement
(speed & direction) directives next.

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) set X_ 390.0


$node_(1) set Y_ 385.0 $node_(1) set Z_ 0.0
Node0 has a starting position of (5,2) while Node1 starts off at location (390,385).

Next produce some node movements,

#
# 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"

# Node_(1) then starts to move away from node_(0)


$ns_ at 100.0 "$node_(1) setdest 490.0 480.0 15.0"

S.V.N.I.T, SURAT Page 91


EC:302 DCN 2021

$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.

Next setup traffic flow between the two nodes as follows:

# TCP connections between node_(0) and node_(1)

set tcp [new Agent/TCP]


$tcp set class_ 2
set sink [new Agent/TCPSink] $ns_
attach-agent $node_(0) $tcp
$ns_ attach-agent $node_(1) $sink
$ns_ connect $tcp $sink set ftp
[new Application/FTP]
$ftp attach-agent $tcp
$ns_ at 10.0 "$ftp start"

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,

puts "Starting Simulation..." $ns_ run

Note: Source obtained from http://www.isi.edu/nsnam/ns/tutorial/

S.V.N.I.T, SURAT Page 92


EC:302 DCN 2021

NS-2 Programming (Tcl Script):


# 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 mobilenodes

set ns [new Simulator]

#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

#Create Topology => keeps track of mobile node movements


#within topology boundary
set topo [new Topography]

#defining topological boundary


$topo load_flatgrid 500 500

#Create object God(General Operations Directory)


#stores numbers of mobile nodes and table of
#shortest number of hops required to reach from one node to other
create-god $val(nn)

#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) \

S.V.N.I.T, SURAT Page 93


EC:302 DCN 2021

-topoInstance $topo \
-channelType $val(chan) \
-agentTrace ON \
-routerTrace ON \
-macTrace OFF \
-movementTrace OFF

#Creating two nodes


set node(0) [$ns node]
$node(0) random-motion 0
set node(1) [$ns node]
$node(1) random-motion 0
#disable random motion

#Initializing nodes positions


#node0 at (5,2,0)
$node(0) set X_ 5.0
$node(0) set Y_ 2.0
$node(0) set Z_ 0.0
$ns initial_node_pos $node(0) 20

#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

#Producing Node Movements


#node1 towards node0
$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"
#node1 away from node0
$ns at 100.0 "$node(1) setdest 490.0 480.0 15.0"

#Setup traffic b/w two nodes


set tcp [new Agent/TCP]
$tcp set class_ 2
set sink [new Agent/TCPSink]
$ns attach-agent $node(0) $tcp
$ns attach-agent $node(1) $sink
$ns connect $tcp $sink
set ftp [new Application/FTP]

S.V.N.I.T, SURAT Page 94


EC:302 DCN 2021

$ftp attach-agent $tcp


$ns at 10.0 "$ftp start"

#Defining Stop: Mobilenodes resets


$ns at 150.0 "$node(0) reset"
$ns at 150.0 "$node(1) reset"
$ns at 150.0001 "stop"
$ns at 150.0002 "puts \"NS EXITING...\" ; $ns halt"
proc stop {} {
global ns tracefd namfile
$ns flush-trace
close $tracefd
close $namfile
exec nam prac11.nam &
exit 0
}

puts "Starting Simulation..."


$ns run

RESULT:
(i) Start

S.V.N.I.T, SURAT Page 95


EC:302 DCN 2021

(ii) Connection Establishment

(iii) FTP

S.V.N.I.T, SURAT Page 96


EC:302 DCN 2021

(iv) Connection Loosing

(v) Connection Termination

S.V.N.I.T, SURAT Page 97


EC:302 DCN 2021

(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.

Signature of the Teacher

S.V.N.I.T, SURAT Page 98

You might also like