Master Copy of Nework Lab 2021 Regulation Lab Manual
Master Copy of Nework Lab 2021 Regulation Lab Manual
Master Copy of Nework Lab 2021 Regulation Lab Manual
To produce highly competent Electrical and Electronics Engineers with professional skills and a sense
of ethics to meet the demands of technologically advancing society.
Empowering the students with up-to-date knowledge and technological skills in Electrical and
Electronics Engineering thrust areas.
Providing a rigorous practical training through industrial collaboration to produce Electrical and
Electronics Engineers with good design experience.
Adopting effective teaching learning methodologies and value added courses to create Electrical and
Electronics Engineers with a strong fundamental knowledge.
Enabling the students to be “life-long” learners to meet intellectual, ethical and career challenges.
i
Program Educational Objectives (PEOs)
Graduates will have adequate knowledge in basic science, mathematics and engineering necessary
to formulate, solve and analyse electrical and electronics problems.
Graduates will have the ability to apply engineering & management skills in their own / team
projects in multidisciplinary environment, leading to successful careers and research.
Graduates will have ability to engage in lifelong learning and an appreciation for professional
ethical behaviour.
Graduates will demonstrate technical knowledge and ethical values for professional development
to meet the societal needs.
ii
Communication: Communicate effectively on complex engineering activities with the engineering
community and with society at large, such as, being able to comprehend and write effective reports
and design documentation, make effective presentations, and give and receive clear instructions.
Project management and finance: Demonstrate knowledge and understanding of the engineering
and management principles and apply these to one’s own work, as a member and leader in a team,
to manage projects and in multidisciplinary environments.
Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
PSO1: Model and analyze the performance of Electrical Machines, Control and Instrumentation
systems and Power and Power Electronic systems.
PSO2: Design the hardware and software requirements for the development of Electrical drives and
Industrial Automation systems.
PSO3: Provide socially acceptable technical solutions to complex electrical engineering problems with
the application of modern and appropriate techniques for sustainable development.
PSO4: Apply the knowledge of ethical standards and management principles required to work in a team.
iii
INSTRUCTIONS TO STUDENTS
Students should wear Uniforms and Coats neatly during the lab session
Students should maintain silence during lab hours; roaming around the lab during lab session is
not permitted
Programs should be written in the manual and well prepared for the current exercise before
coming to the session
Experiments should be completed within the Specified Lab Session
Before Every Session, Last Session lab exercise & record should be completed and get it verified
by the faculty
In the Record Note, Flow Chart and Outputs should be written on the left side, while Aim,
Algorithm & Result should be written on the right side.
Programs (Printed) should be placed on the right side
Marks for each lab exercise is awarded as follows:
Performance 25 Marks
Viva 10 Marks
Record 15 Marks
Total 50 Marks
iv
PREFACE
The first Networks Lab manual (Regulation 2021) was prepared in the academic year 2022 -2023(Odd
semester) for the V semester CSE students. Course objectives, outcomes and mapping the lab exercises
to the outcomes are included in this manual. Various neccessary header files and study of socket
prograaming with syntax and examples are included. New exercises are added besides university
syllabus. Viva questions related to the exercise is included at the end of each lab exercise. We want to
thank Dr.K.Vijayalakshmi, HOD/CSE for providing valuable suggestions in preparing this students
centric manual. We would also like to thank other faculty members who helped us in many ways
v
CONTENTS
Syllabus
CO - Mapping
Virtual Lab
Ex. No.
Learn to use commands like tcpdump, netstat, ifconfig, nslookup and trace route.
1. Capture ping and trace route PDUs using a network protocol analyzer and
examine.
2. Write a HTTP web client program to download a web page using TCP sockets
Applications using TCP sockets like:
3. a. Echo client and echo server
b. Chat
4. Simulation of DNS using UDP sockets.
5.
Use a tool like Wirshark to capture packets and examine the packets
6.
Write a code simulating ARP /RARP protocols
References
vi
CS3591 – NETWORKS LABORATORY
Syllabus 2021 Regulation
LTPC
0042
OBJECTIVES:
LIST OF EXPERIMENTS
1. Learn to use commands like tcpdump, netstat, ifconfig, nslookup and traceroute. Capture
ping and traceroute PDUs using a network protocol analyzer and examine.
2. Write a HTTP web client program to download a web page using TCP sockets.
3. Applications using TCP sockets like:
a) Echo client and echo server
b) Chat
4. Simulation of DNS using UDP sockets.
5. Use a tool like Wirshark to capture packets and examine the packets
6. Write a code simulating ARP /RARP protocols.
7. Study of Network simulator (NS) and Simulation of Congestion Control Algorithms using
NS.
8. Study of TCP/UDP performance using Simulation tool.
9. Simulation of Distance Vector/ Link State Routing algorithm.
10. Simulation of error correction code (like CRC).
TOTAL: 75 PERIODS
OUTCOMES:
Upon Completion of the course, the students will be able to:
CO1: Elucidate the basic layers and its functions in computer networks.
CO2: Predict the detailed inner workings of Transport layer.
CO3: Describe the various functions in the network layers and network protocols
CO4: Apply the routing algorithms for a given problem.
CO5: Classify the different type of network interfaces and their uses by identifying basic Network
components, choosing appropriate network type and media
1
RAMCO INSTITUTE OF TECHNOLOGY
Department of Computer Science and Engineering
Academic Year: 2023 - 2024(Odd Semester)
Course Objectives:
1. Understand the concept of layering in networks.
2. Know the functions of protocols of each layer of TCP/IP protocol suite.
3. Visualize the end-to-end flow of information.
4. Learn the functions of network layer and the various routing protocols
5. Familiarize the functions and protocols of the Transport layer
Course Outcomes:
After completion of the course, it is expected that the students will be able to
1. Elucidate the basic layers and its functions in computer networks.
2. Predict the detailed inner workings of Transport layer.
3. Describe the various functions in the network layers and network protocols
4. Apply the routing algorithms for a given problem.
5. Classify the different type of network interfaces and their uses by identifying basic Network
components, choosing appropriate network type and media
Assessment Methods followed:
1. Continuous record, presentation and lab exercise completion.
2. Model practical examination is conducted to assess the performance of the students.
End semester practical examination is conducted by Anna University to assess the overall learning of
the students in the course.
2
CO - MAPPING
5.
Use a tool like Wireshark to capture packets and examine the packets CO2
6.
Write a code simulating ARP /RARP protocols CO3
9.
Simulation of Distance Vector/ Link State Routing algorithm. CO4
3
STUDY OF HEADER FILES
1. stdio.h:
Has standard input and output library providing simple and efficient buffered stream IO interface.
2. unistd.h:
3. string.h:
This header file is used to perform string manipulation operations on NULL terminated strings.
4. stdlib.h:
This header file contains the utility functions such as string conversion routines, memory allocation
routines, random number generator, etc.
5. sys/types.h:
6. sys/socket.h:
The socket functions can be defined as taking pointers to the generic socket address structure called
sockaddr.
7. netinet/in.h:
Defines the IPv4 socket address structure commonly called Internet socket address structure called
sockaddr_in.
8. netdb.h:
Defines the structure hostent for using the system call gethostbyname to get the network host entry.
9. time.h:
Has structures and functions to get the system date and time and to perform time manipulation
functions. We use the function ctime(), that is defined in this header file , to calculate the current
date and time.
4
10. sys/stat.h:
Contains the structure stat to test a descriptor to see if it is of a specified type. Also it is used to
display file or file system status.
11. sys/ioctl.h:
Macros and defines used in specifying an ioctl request are located in this header file. We use the
function ioctl() that is defined in this header file. ioctl() function is used to perform ARP cache
operations.
12. pcap.h:
Has function definitions that are required for packet capturing. Some of the functions are
pcap_lookupdev(),pcap_open_live() and pcap_loop(). pcap_lookupdev() is used to initialize the
network device.The device to be sniffed is opened using the pcap_open_live(). Pcap_loop()
determines the number of packets to be sniffed.
13. net/if_arp.h:
Contains the definitions for Address Resolution Protocol. We use this to manipulate the ARP request
structure and its data members arp_pa,arp_dev and arp_ha. The arp_ha structure’s data member
sa_data[ ] has the hardware address.
14. errno.h:
It sets an error number when an error and that error can be displayed using perror function. It has
symbolic error names. The error number is never set to zero by any library function.
15. arpa/inet.h:
This is used to convert internet addresses between ASCII strings and network byte ordered binary
values (values that are stored in socket address structures). It is used for inet_aton, inet_addr, inet_n
to a function.
5
STUDY OF SOCKET PROGRAMMING & CLIENT - SERVER MODEL
1. Socket Interface
It is based on UNIX and defines a set of system calls (procedures) that are an extension of
system calls used to access files.
A "socket" is a loose term used to describe "an end point for communication." The traditional
Berkley Socket API is a set of C function calls used to support network communication
- In UNIX:
#include <sys/types.h> /* basic system data types */
#include <sys/socket.h> /* basic socket definitions */
#include <sys/time.h> /* timeval{} for select() */
#include <time.h> /* timespec{} for pselect() */
#include <netinet/in.h> /* sockaddr_in{} and other Internet defns */
#include <arpa/inet.h> /* inet(3) functions */
#include <errno.h>
#include <fcntl.h> /* for nonblocking, on windows don't use fnctl(), use ioctlsocket() */
#include <netdb.h>
#include <signal.h>
6
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h> /* for S_xxx file mode constants */
#include <unistd.h> /* this file is typically only for Linux *nix OS's */
#include <sys/wait.h>
#include <sys/un.h> /* for Unix domain sockets */
#include <stdarg.h> /* for sdprintf */
- In Windows
#include <windows.h>
#include <sys/types.h>
#include <winsock.h>
Networking Terms
packet - the smallest unit that can be transferred “through” the network by itself
protocol - a set of rules and conventions between the communicating participants
A collection of protocol layers is referred to as a “protocol suite”, “protocol family” or
“protocol stack”. TCP/IP is one such protocol suite.
7
service type symbolic name comment
datagram SOCK_DGRAM UDP protocol in AF_INET
reliable, in-order SOCK_STREAM TCP protocol in AF_INET
raw socket SOCK_RAW direct access to network layer
o sockfd is an integer (similar to a file descriptor) returned by the socket call. This is the
Socket Descriptor, which uniquely defines the created socket if the creation is
Successful. It returns –1 if there is an error. The Socket Descriptor is used by other
functions to refer the socket.
Example:
if (( sockfd = socket(AF_INET,SOCK_STREAM,0)) == -1) // TCP
{ printf(": error opening socket");
exit(-1); }
Example:
if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) // UDP
{ /* handle error */ }
o localaddr is the local address returned by the bind call. [ i.e. ] *localaddr is a pointer to
the struct sockaddr which is used in the bind call
o socklen_t localaddrlen is an interger returning the size of the struct sockaddr which can
be obtained by the call sizeof(struct sockaddr)
Example:
if ( bind(sock, (struct sockaddr *) &sock_addr, sizeof(sock_addr)) < 0)
{
printf(": error binding socket to local address");
exit(-1);
}
o queue-size indicates the number of connection requests which can be queued by the
system while the local process has not yet issued the accept call.
o foreign-address is the pointer to the address of the foreign (client) process that has
requested the connection returned by the accept call.
o foreign-address is the address of foreign (server) process returned by the connect call.
9
Reading from a socket: recvfrom() - Connectionless
int recvfrom (int sockfd, char *buff, int bufflen, int flags, struct sockaddr *fromaddrptr, int
*addresslen)
sockfd is variable assigned socket() return value.
*buff is a set of consecutive mem. locs. into which received data to be written
*fromaddrptr is address of sockaddr_in structure containing address info of socket that sent
this data. A returned value.
10
Function
action
name
convert 32-bit host format to Network byte
htonl
order
convert Network byte order to 32-bit host
ntohl
format
convert 16-bit host format to Network byte
htons
order
convert Network byte order to 16-bit host
ntos
format
#include <string.h>
void bzero(void *dest, size_tnbytes);
void bcopy(const void *src, void *dest, size_tnbytes);
int bcmp(const void *ptr1, const void *ptr2, size_tnbytes);
Return:0 if equal, nonzero if unequal
#include <string.h>
void *memset(void *dest, intc, size_tnbytes);
void *memcpy(void *dest, const void *src, size_tnbytes);
int memcmp(const void *ptr1, const void *ptr2, size_tnbytes);
Internet addressing
each Internet host has one or more globally-unique 32-bit IP addresses
host may have two or more addresses
o address associated with each interface card
dotted decimal notation:
o 4 decimal integers, each specifying one byte of IP address:
11
The gethostbyname() function accepts the domain name of the host and returns structured
information called hostent that is actually the content of a resource record.
The prototype of the function gethostbyname() is given as
Struct hostent *gethostbyname (const char *hostname)
The hostent structure is
struct hostent {
char *h_name;
char **h_aliases:
int h_addrtype;
int h_length;
char **h_addr_list;
}
• h_name – Official name of the host.
• h_aliases – A NULL-terminated array of alternate names for the host.
• h_addrtype – The type of address being returned; usually AF_INET.
• h_length – The length of the address in bytes.
• h_addr_list – A zero-terminated array of network addresses for the host. Host addresses are in Network
Byte Order.
/*
** getip.c - a hostname lookup demo
Generic Socket Address Structure -This structure holds socket address information for many types of
sockets:
struct sockaddr {
unsigned short sa_family; // address family, AF_xxx
char sa_data[14]; // 14 bytes of protocol address
};
Where
sa_family – Addressing Family – by default it is AF_INET
sa_data - contains a destination address and port number for the socket.
Where
sin_family - Addressing Family – by default it is AF_INET
sin_port -16-bit port number
sin_zero - is included to pad the structure to the length of a struct sockaddr. It is should be
set to all zeros with the function memset().
Internet Address
12
struct in_addr
{
u_long s_addr; /* 32 bit host addr.,nbo */
};
Filling the sockaddr_in structure
Example :
sock_addr.sin_addr.s_addr = htonl(INADDR_ANY);
sock_addr.sin_port = htons(0);
sock_addr.sin_family = AF_INET;
1. inet_aton
2. inet_ntoa
inet_ntoa inet_aton
Dotted Decimal Address
An Example Scenario
As an example, consider the socket system calls for a connection-oriented protocol.
13
RESULT:
Thus the basic functions used for Socket Programming was studied successfully.
14
VIRTUAL LAB
To motivate students to conduct experiments by exciting their curiosity. This would help them in
learning basic and advanced concepts through remote experimentation.
It offers a complete Learning Management System around the Virtual Labs where the students
can benefit the various tools for learning, including additional web-resources, video-lectures,
animated demonstrations and self-evaluation.
Objective:
To understand the different topologies for familiarizing the data flow with in a wireless sensor network.
To implement and evaluate different topologies for a wireless sensor network
15
.
Ex.No: 1 Learn to use commands like tcpdump, netstat, ifconfig, nslookup and trace route. Capture
Date: ping and trace route PDUs using a network
Aim:
To learn to use commands like tcpdump, netstat, ifconfig, nslookup and trace route and
Capture ping and trace route PDUs using a network
Tcpdump:
Tcpdump is a most powerful and widely used command-line packets sniffer or package analyzer
tool which is used to capture or filter TCP/IP packets that received or transferred over a network
on a specific interface. It is available under most of the Linux/Unix based operating system.
It is available under most of the Linux/Unix based operating systems. tcpdump also gives us an
option to save captured packets in a file for future analysis. It saves the file in a pcap format,
that can be viewed by tcpdump command or a open source GUI based tool called Wireshark
(Network Protocol Analyzer) that reads tcpdump pcap format files.
Output: The command screen will scroll up until you interrupt and when we
execute tcpdump command it will captures from all the interfaces, however with -i switch only capture
from desire interface.
Netstat: netstat (network statistics) is a command-line network utility tool that displays network
connections for the Transmission Control Protocol (both incoming and outgoing), routing tables, and a
number of network interface (network interface controller or software-defined network interface)
The information that is displayed includes the protocol, the local address, the remote (foreign) address,
and the connection state. Note that the various IP addresses include port information as well.
Syntax
netstat [-a] [-e] [-n] [-o] [-p Protocol] [-r] [-s] [Interval]
16
Parameters
Used without parameters displays active TCP connections.
-a
Displays all active TCP connections and the TCP and UDP ports on which the computer is listening.
-e Displays Ethernet statistics, such as the number of bytes and packets sent and received. This
parameter can be combined with -s.
-n
Displays active TCP connections, however, addresses and port numbers are expressed numerically and
no attempt is made to determine names.
-o
Displays active TCP connections and includes the process ID (PID) for each connection. You can find
the application based on the PID on the Processes tab in Windows Task Manager. This parameter can
be combined with -a, -n, and -p.
-p
Shows connections for the protocol specified by Protocol. In this case, the Protocol can be tcp, udp,
tcpv6, or udpv6. If this parameter is used with -s to display statistics by protocol, Protocol can be tcp,
udp, icmp, ip, tcpv6, udpv6, icmpv6, or ipv6.
-s
Displays statistics by protocol. By default, statistics are shown for the TCP,UDP, ICMP, and IP
protocols. If the IPv6 protocol for Windows XP is installed, statistics are shown for the TCP over IPv6,
UDP over IPv6, ICMPv6, and IPv6 protocols. The -p parameter can be used to specify a set of protocols.
-r
Displays the contents of the IP routing table. This is equivalent to the route print command.
Redisplays the selected information every Interval seconds. Press CTRL+C stop the redisplay.
State Description
Indicates that the server has received an ACK signal from the client and the
CLOSED
connection is closed
Indicates that the server has received the first FIN signal from the client and
CLOSE_WAIT
the connection is in the process of being closed
Indicates that the server received the SYN signal from the client and the
ESTABLISHED
session is established
FIN_WAIT_1 Indicates that the connection is still active but not currently being used
17
ifconfig: ifconfig stands for "interface configuration." It is used to view and change the configuration
of the network interfaces on your system. When a network interface is active, it can send and receive
data; when it is inactive, it is not able to transmit or receive. You can use ifconfig to change the status
of a network interface from inactive to active, or vice-versa.
An important additional feature of ipconfig is to force refreshing of the DHCP IP address of the host
computer to request a different IP address. This is done using two commands in sequence.
First, ipconfig /release is executed to force the client to immediately give up its lease by sending the
server a DHCP release notification which updates the server's status information and marks the old
client's IP address as "available". Then, the command ipconfig /renew is executed to request a new IP
address. Where a computer is connected to a cable or DSL modem, it may have to be plugged directly
into the modem network port to bypass the router, before using ipconfig /release and turning off the
power for a period of time, to ensure that the old IP address is taken by another computer.
nslookup: The nslookup (which stands for name server lookup) command is a network utility program
used to obtain information about internet servers
18
it is a network administration command-line tool available in many computer operating systems for
querying the Domain Name System (DNS) to obtain domain name or IP address mapping, or other DNS
records.
traceroute: Traceroute is a command which can show you the path a packet of information takes from
your computer to one you specify. It will list all the routers it passes through until it reaches its
destination, or fails to and is discarded. In addition to this, it will tell you how long each 'hop' from
router to router takes.
tracert www.google.com
With the tracert command shown above, we're asking tracert to show us the path from the local computer
all the way to the network device with the hostname www.google.com. Tracing route to
www.l.google.com [209.85.225.104] over a maximum of 30 hops: 1
RESULT:
Thus the COMMANDS like tcpdump, netstat, ifconfig, nslookup and traceroute. Capture ping and
traceroute PDUs using a network protocol analyzer and examined successfully.
19
Viva Questions
20
Ex.No: 2
HTTP WEB CLIENT PROGRAM TO DOWNLOAD A WEB PAGE
Date: USING TCP SOCKETS
Aim:
To develop Http web client program to download a webpage using TCP socket.
Explanation
HTTP means HyperText Transfer Protocol. HTTP is the underlying protocol used by the World
Wide Web and this protocol defines how messages are formatted and transmitted, and what actions Web
servers and browsers should take in response to various commands
Whenever you issue a URL from your browser to get a web resource using HTTP,
e.g. http://www.nowhere123.com/index.html, the browser turns the URL into a request message and
sends it to the HTTP server. The HTTP server interprets the request message, and returns you an
appropriate response message, which is either the resource you requested or an error message. This
process is illustrated below:
HTTP/1.1 200 OK
Date: Sun, 18 Oct 2009 08:56:53 GMT
Server: Apache/2.2.14 (Win32)
Last-Modified: Sat, 20 Nov 2004 07:16:26 GMT
ETag: "10000000565a5-2c-3e94b66c2e680"
Accept-Ranges: bytes
21
Content-Length: 44
Connection: close
Content-Type: text/html
X-Pad: avoid browser bug
<html><body><h1>It works!</h1></body></html>
Algorithm:
Server:
1.Start the program
2. Create the socket and accepts connection from the client.
3. When this request message reaches the server, the server can take either one of these actions:
a. The server interprets the request received, maps the request into a file under the server's
document directory, and returns the file requested to the client.
b. The server interprets the request received, maps the request into a program kept in the server,
executes the program, and returns the output of the program to the client.
Client:
1. Start the program
2. Create the socket and connect to the server using connect() function
3.Send the file name the get request to the server.
//HTTP SERVER
#include<stdio.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<string.h>
int main()
{
FILE *f;
int sd,len,i=0,l,s,sd1,si,eof;
char req[20],status[50]={"HTTP/1/1 200 OK"},dateinfo[50]={"Mon,16mar 2015"
type[50]={"text/html"},contlength[50]={"150"};
struct sockaddr_in ser;
struct sockaddr_in cli;
char buf[50],msg[50],rmsg[50];
if((sd=socket(AF_INET,SOCK_STREAM,0))<0)
{
printf("Error");
return 0;
}
bzero(&ser,sizeof(ser));
ser.sin_family=AF_INET;
ser.sin_port=htons(7879);
ser.sin_addr.s_addr=htonl(INADDR_ANY);
if((bind(sd,(struct sockaddr*)&ser,sizeof(ser)))<0)
{
printf("Binding error");
return 0;
}
22
if((listen(sd,5))<0)
{
printf("Listening error");
return 0;
}
si=sizeof(cli);
if((sd1=accept(sd,(struct sockaddr*)&cli,&si))<0)
{
printf("Accepting error");
return 0;
}
recv(sd1,req,50,0);
recv(sd1,msg,50,0);
printf("\nThe File Name Is %s\n",msg);
if(strcmp(req,"GET")==0)
{
f=fopen(msg,"r");
if(f!=NULL)
{
printf("File is present in the server");
send(sd1,status,sizeof(status),0);
send(sd1,dateinfo,sizeof(dateinfo),0);
send(sd1,conttype,sizeof(conttype),0);
send(sd1,contlength,sizeof(contlength),0);
do
{
bzero(&buf,50);
fread(&buf,50,1,f);
send(sd1,buf,50,0);
}while(!feof(f));
}
}
send(sd1,"COMPLETED",20,0);
fclose(f);
close(sd1);
}
HTTP Client:
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<string.h>
main()
{
int sd,i=0,len,eof;
struct sockaddr_in ser;
char buf[50],rmsg[50],source[15],dest[15];
char res1[50],res2[50],res3[50],res4[50];
if((sd=socket(AF_INET,SOCK_STREAM,0))<0)
{
printf("Error on Socket creation");
return 0;
}
23
bzero(&ser,sizeof(ser));
ser.sin_family=AF_INET;
ser.sin_port=htons(7879);
ser.sin_addr.s_addr=htonl(INADDR_ANY);
if((connect(sd,(struct sockaddr *)&ser,sizeof(ser)))==-1)
{
printf("Error on Connect");
return 0;
}
printf("Enter the source file name:");
scanf("%s",source);
send(sd,"GET",sizeof("GET"),0);
send(sd,source,50,0);
printf("Server response\n");
recv(sd,res1,50,0);
recv(sd,res2,50,0);
recv(sd,res3,50,0);
recv(sd,res4,50,0);
printf("%s",res1);
printf("%s",res2);
printf("%s",res3);
printf("%s",res4);
recv(sd,rmsg,50,0);
while((strcmp(rmsg,"COMPLETED"))!=0)
{
printf("%s",rmsg);
bzero(&rmsg,50);
recv(sd,rmsg,50,0);
}
printf("Response Completed\n");
close(sd);
}
Results: Thus the socket program for HTTP using TCP socket was written and executed successfully
Viva Questions:
24
Ex.No: 3 a APPLICATIONS USING TCP SOCKETS
Date: ECHO CLIENT AND ECHO SERVER
AIM:
To write a program for implementing echo communication using TCP.
METHODOLOGY:
Transmission Control Protocol (TCP):
The Transmission Control Protocol is one of the core protocols of the Internet Protocol Suite.
TCP operates at a higher level, concerned only with the two end systems. TCP provides reliable, ordered
delivery of a stream of bytes from a program on one computer to another program on another computer.
TCP controls segment size, flow control, the rate at which data is exchanged, and network traffic
congestion.
TCP protocol operations may be divided into three phases. Connections must be properly
established in a multi-step handshake process (connection establishment) before entering the data
transfer phase. After data transmission is completed, the connection termination closes established
virtual circuits and releases all allocated resources.
Server:
Step 1: start a program.
Step 2: create a socket with address family AF_INET, type SOCK_STREAM and default
protocol.
Step 3: Initialize the socket and assign any port number.
Step 4: Bind the server to the socket using bind() function.
Step 5: Establish the listen queue using the listen function.
Step 6: wait for client program on request, establish a connection using accept function.
Step 7: Repeat steps 8-10 until the server sends exit.
Step 8: Receive the message from the client using recv() and display the message.
Step 9: If the client message is exit go to step 11.
Step 10: Get the server message and send it to client using send() function.
Step 11: close the connection.
Step 12: Go to step 6.
25
Client:
Step 1: Start.
Step 2: Create a socket with address family AF_INET type SOCK_STERAM and default
protocol.
Step 3: Initialize the socket and set it attributes set the required port number.
Step 4: Connect to the server using connect() function to initialize the request.
Step 5: Repeat steps 6-8 until server sends bye
Step 6: Accept the client message and send it to the server using send function.
Step 7: If the client message is exit go to step 9.
Step 8: Receive the message from the server using recv() and display the message.
Step 9: stop.
Output:
[test@ritlinux ~]$ cc tcpechoser.c
[test@ritlinux ~]$ ./a.out
The socket is created successfully
Binding Completed
Listening is completed
Client is Accepted
Message received from client: hai
Message received from client: hello
Message received from client: END
[test@ritlinux ~]$ cc tcpechocli.c
[test@ritlinux ~]$ ./a.out
Socket created successfully
Connection established successfully
Enter the string: hai
The content received from sender is: hai
Enter the string: hello
The content received from sender is: hello
Enter the string: END
The content received from sender is: END
Result:
Thus the socket program for echo using TCP was written and executed successfully.
28
Ex. No: 3b
DATE:
SOCKET PROGRAM FOR CHAT USING TCP
Aim:
To write a socket program for chat between server and client using TCP
Algorithm:
Server side
1) Create a socket & bind it.
2) Receive message from client.
3) Print the message.
4) Send message to client
5) If message is “Data Sent” then end the program.
Client side
1) Create a socket.
2) Get the IP address.
3) Send message to server
4) Receiver message from client.
5) If message is “Data Sent” then end the program.
Coding:
TCP CHAT SERVER
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
int sid,con,sd,rd;
struct sockaddr_in sin;
char buf[10];
sid=socket(PF_INET,SOCK_STREAM,0);
if(sid == -1)
{
printf("\n Error in creating the socket \n");
exit(-1);
}
printf("\n Socket created successfully");
memset(&sin,0,sizeof(sin));
sin.sin_family=AF_INET;
sin.sin_port=htons(5190);
sin.sin_addr.s_addr=htonl(INADDR_ANY);
con=connect(sid,(struct sockaddr*)&sin,sizeof(sin));
29
if(con < 0)
{
printf("\n The connection established falied \n");
exit(-1);
}
printf("\n Connection established successfully \n");
do
{
printf(" Enter the string: ");
scanf("%s",buf);
sd=send(sid,buf,10,0);
if(sd < 0)
{
printf("\n Error in sending the data to the server \n");
exit(-1);
}
rd=read(sid,buf,10);
if(rd < 0)
{
printf("\n Error in reading the data send by the server \n");
exit(-1);
}
printf(" The content received from sender is: %s \n",buf);
}while(strcasecmp(buf,"END")!=0);
shutdown(sid,2);
close(sid);
}
sid=socket(PF_INET,SOCK_STREAM,0);
if(sid == -1)
{
printf("\n Error in creating socket \n");
exit(-1);
}
printf("\n The socket is created successfully");
memset(&sin,0,sizeof(sin));
sin.sin_family=AF_INET;
sin.sin_port=htons(5190);
30
sin.sin_addr.s_addr=htonl(INADDR_ANY);
bd=bind(sid,(struct sockaddr*)&sin,sizeof(sin));
if(bd < 0)
{
printf("\n Binding failed \n");
exit(-1);
}
printf("\n Binding Completed");
lis=listen(sid,5);
if(lis < 0)
{
printf("\n Error in listening \n");
exit(-1);
}
printf("\n Listening is completed");
len=sizeof(sin);
acptd=accept(sid,(struct sockaddr*)&sin,&len);
if(accept < 0)
{
printf("\n Error in Accepting \n");
exit(-1);
}
printf("\n Client is Accepted \n");
do
{
rd=read(acptd,buf,10);
if(rd < 0)
{
printf("\n Error in receiving the date from the client \n");
exit(-1);
}
printf(" Message received from client: %s \n",buf);
printf("Enter string to send");
scanf("%s",buf);
sd=send(acptd,buf,10,0);
if(sd < 0)
{
printf("\n Error in sending the data to the client \n");
exit(-1);
}
}while(strcasecmp(buf,"END")!=0);
shutdown(sid,2);
close(sid);
}
OUTPUT:
[sudha@ritlinux tcp]$ cc tcpchatserver.c
[sudha@ritlinux tcp]$ ./a.out
The socket is created successfully
Binding Completed
Listening is completed
Client is Accepted
Message received from client: hai
31
Enter string to sendhello
Message received from client: welcome
Enter string to sendEND
[sudha@ritlinux tcp]$ cc tcpchatclient.c
[sudha@ritlinux tcp]$ ./a.out
Socket created successfully
Connection established successfully
Enter the string: hai
The content received from sender is: hello
Enter the string: welcome
The content received from sender is: END
Result:
Thus the socket program for the implementation of chat using TCP written and executed successfully
32
Ex.No: 4 Simulation of DNS using UDP sockets.
Date:
AIM:
To write a program for simulation of DNS using UDP sockets.
Explanation
Name server
In UNIX the resolver is accessed by using the library functions "gethostbyname" and
"gethostbyaddr". The resolver will send requests to the name servers to return information requested by
the user. The requesting computer tries to connect to the name server using its IP address rather than the
name.
Structure and message format:
The drawing below shows a partial DNS hierarchy. At the top is what is called the root and it is
the start of all other branches in the DNS tree. It is designated with a period. Each branch moves down
from level to level. When referring to DNS addresses, they are referred to from the bottom up with the
root designator (period) at the far right. Example: "myhost.mycompany.com.”
33
Algorithm:
Server:
1. Start the program.
2. Create the socket, establish a connection using accept function.
3. Get the domain name from the client.
4. Match the domain name to the corresponding IP address and send it to client.
5. Close the connection.
6. Stop the program.
Client:
1. Start the program.
2. Create the socket and Connect to the server using connect() function.
3. Send the domain name to the DNS server.
4. Receive the corresponding IP address from the server.
5. Display the address.
6. Close the socket.
DNS Server1:
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<unistd.h>
#include<time.h>
int main()
{
int sid,i,j,len,k=0,sid1;
char buf1[200],buf2[20],buf3[20],buf[200],msg[200];
struct sockaddr_in sin,sin1;
sid=socket(PF_INET,SOCK_DGRAM,0);
memset(&sin,0,sizeof(sin));
34
sin.sin_family=AF_INET;
sin.sin_port=htons(5111);
sin.sin_addr.s_addr=htonl(INADDR_ANY);
len=sizeof(sin);
bind(sid,(struct sockaddr *)&sin,len);
recvfrom(sid,&msg,sizeof(msg),0,(struct sockaddr *)&sin,&len);
if(!strcasecmp(msg,"Gmail"))
{
strcpy(buf,"124.124.252.113");
strcpy(buf1,"Server1");
}
else if(!strcasecmp(msg,"Yahoomail"))
{
strcpy(buf,"25.255.169.86");
strcpy(buf1,"server1");
}
else if(!strcasecmp(msg,"Rediffmail"))
{
strcpy(buf,"225.176.16.254");
strcpy(buf1,"server1");
}
else
{
strcpy(buf1,"server2");
sid1=socket(PF_INET,SOCK_DGRAM,0);
memset(&sin1,0,sizeof(sin1));
sin1.sin_family=AF_INET;
sin1.sin_port=htons(4111);
sin1.sin_addr.s_addr=htonl(INADDR_ANY);
len=sizeof(sin1);
sendto(sid1,&msg,sizeof(msg),0,(struct sockaddr *)&sin1,len);
recvfrom(sid1,&buf,sizeof(buf),0,(struct sockaddr *)&sin1,&len);
}
sendto(sid,&buf,sizeof(buf),0,(struct sockaddr *)&sin,len);
sendto(sid,&buf1,sizeof(buf),0,(struct sockaddr *)&sin,len);
printf("\n Disconnected \n");
close(sid);
shutdown(sid,0);
}
DNS Server2:
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<unistd.h>
35
#include<time.h>
int main()
{
int sid,i,j,len,k=0;
char buf1[20],buf2[20],buf3[20],buf[200],msg[200];
struct sockaddr_in sin;
sid=socket(PF_INET,SOCK_DGRAM,0);
memset(&sin,0,sizeof(sin));
sin.sin_family=AF_INET;
sin.sin_port=htons(4111);
sin.sin_addr.s_addr=htonl(INADDR_ANY);
len=sizeof(sin);
bind(sid,(struct sockaddr *)&sin,len);
recvfrom(sid,&msg,sizeof(msg),0,(struct sockaddr *)&sin,&len);
if(!strcasecmp(msg,"Wikipedia"))
{
strcpy(buf,"208.80.152.2");
sendto(sid,&buf,sizeof(buf),0,(struct sockaddr *)&sin,len);
}
else if(!strcasecmp(msg,"Google"))
{
strcpy(buf,"126.83.15.245");
sendto(sid,&buf,sizeof(buf),0,(struct sockaddr *)&sin,len);
}
else if(!strcasecmp(msg,"Bing"))
{
strcpy(buf,"88.280.125.20");
sendto(sid,&buf,sizeof(buf),0,(struct sockaddr *)&sin,len);
}
printf("\n Disconnected \n");
close(sid);
shutdown(sid,0);
}
DNS Client
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<unistd.h>
int main()
{
int sid,i,j,len,k=0,sid1;
char buf[200],msg[200],buf1[200];
struct sockaddr_in sin,sin1;
sid=socket(PF_INET,SOCK_DGRAM,0);
36
memset(&sin,0,sizeof(sin));
sin.sin_family=AF_INET;
sin.sin_port=htons(5111);
sin.sin_addr.s_addr=htonl(INADDR_ANY);
len=sizeof(sin);
printf("\nEnter website name:");
scanf("%s",msg);
sendto(sid,&msg,sizeof(msg),0,(struct sockaddr *)&sin,len);
recvfrom(sid,&buf,sizeof(buf),0,(struct sockaddr *)&sin,&len);
recvfrom(sid,&buf1,sizeof(buf),0,(struct sockaddr *)&sin,&len);
printf("IP:%s\t From->%s\n",buf,buf1);
close(sid);
shutdown(sid,0);
}
Output
[sudha@ritlinux ~]$ cc dnsser1.c
[sudha@ritlinux ~]$ ./a.out
Disconnected
[sudha@ritlinux ~]$ cc dnsser2.c
[sudha@ritlinux ~]$ ./a.out
Disconnected
[sudha@ritlinux ~]$ cc dnscli.c
[sudha@ritlinux ~]$ ./a.out
Enter website name:Google
IP:126.83.15.245 From->server2
[sudha@ritlinux ~]$ cc ssdnsc.c
[sudha@ritlinux ~]$ ./a.out
Enter website name:Gmail
IP:124.124.252.113 From->Server1
Result:
Thus the program to implement DNS was done and output was verified
37
Viva Questions:
38
Ex.No: 6
USE A TOOL LIKE WIRESHARK TO CAPTURE PACKETS AND EXAMINE
Date:
THE PACKETS
Aim:
To learn to use a tool like Wireshark to capture packets and examine the packets
Wireshark helps:
Network administrators troubleshoot problems across a network
Security engineers examine security issues across a network
QA engineers verify applications
Developers debug protocol implementations
Network users learn about a specific protocol
39
select one or more of the network interfaces using shift+left-click. Once select the network
interface, we can start the capture, and there are several ways to do that.
Click the first button on the toolbar, titled “Start capturing packets.”
40
Analyzing data packets on Wireshark
Wireshark shows you three different panes for inspecting packet data. The Packet List, the top
pane, lists all the packets in the capture. When you click on a packet, the other two panes change
to show you the details about the selected packet. You can also tell if the packet is part of a
conversation. Here are details about each column in the top pane:
No.: This is the number order of the packet captured. The bracket indicates that this
packet is part of a conversation.
Time: This column shows how long after started the capture this particular packet was
captured. You can change this value in the Settings menu to display a different option.
Source: This is the address of the system that sent the packet.
Destination: This is the address of the packet destination.
Protocol: This is the type of packet. For example: TCP, DNS, DHCPv6, or ARP.
Length: This column shows the packet’s length, measured in bytes.
Info: This column shows more information about the packet contents, which will vary
depending on the type of packet.
Wireshark filters
Some of the best features of Wireshark are the capture filters and display filters. Filters allow to
view the capture the way need to see it to troubleshoot the issues at hand. Below are several
filters to get started.
Capture filters limit the captured packets by the chosen filter. If the packets don’t match the
filter, Wireshark won’t save them. Examples of capture filters include:
host IP-address: This filter limits the captured traffic to and from the IP address
net 172.168.0.0/24: This filter captures all traffic on the subnet
dst host IP-address: Capture packets sent to the specified host
port 53: Capture traffic on port 53 only
port not 53 and not arp: Capture all traffic except DNS and ARP traffic
Wireshark display filters change the view of the capture during analysis. After we’ve stopped
the packet capture, use display filters to narrow down the packets in the Packet List to
troubleshoot issue.
41
One of the most useful display filters is:
ip.src==IP-address and ip.dst==IP-address
This filter shows packets sent from one computer (ip.src) to another (ip.dst). we can also
use ip.addr to show packets to and from that IP. Other filters include:
tcp.port eq 25: This filter will show all traffic on port 25, which is usually SMTP traffic
icmp: This filter will show only ICMP traffic in the capture, most likely they are pings
ip.addr != IP_address: This filter shows you all traffic except the traffic to or from the
specified computer
Analysts even build filters to detect specific attacks, like this filter used to detect
the Sasser worm:
ls_ads.opnum==0x09
Result:
Thus the learn to use a tool like Wireshark to capture packets and examine the packets
was verified
Viva Questions:
42
Ex.No: 6
SIMULATING ARP PROTOCOLS
Date:
AIM:
To implement Address Resolution Protocol (ARP) is a protocol for mapping an Internet
Protocol address
Explanation
Address Resolution Protocol (ARP) is a protocol for mapping an Internet Protocol address (IP
address) to a physical machine address that is recognized in the local network. For example, in IP
Version 4, the most common level of IP in use today, an address is 32 bits long. In an Ethernet
local area network, however, addresses for attached devices are 48 bits long. (The physical
machine address is also known as a Media Access Control or MAC address.) A table, usually
called the ARP cache, is used to maintain a correlation between each MAC address and its
corresponding IP address. ARP provides the protocol rules for making this correlation and
providing address conversion in both directions.
When an incoming packet destined for a host machine on a particular local area network arrives
at a gateway, the gateway asks the ARP program to find a physical host or MAC address that
matches the IP address. The ARP program looks in the ARP cache and, if it finds the address,
provides it so that the packet can be converted to the right packet length and format and sent to
the machine. If no entry is found for the IP address, ARP broadcasts a request packet in a special
format to all the machines on the LAN to see if one machine knows that it has that IP address
associated with it. A machine that recognizes the IP address as its own returns a reply so indicating.
ARP updates the ARP cache for future reference and then sends the packet to the MAC address
that replied
APR Server:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
struct ipmac{
char ip[100];
char mac[100];};
int main(){
int sockfd,i,s,a,b;
socklen_t len;
struct sockaddr_in servaddr;
char buff[30],temp[100],ip[100],mac[100];
int flag=0;
43
struct ipmac in[3]={
{"10.1.1.8","44:dd:22:11:33"},
{"127.0.0.1","33:aa:fe:4e:2d"},
{"10.1.8.5","23:a3:5d:33:9d"},
};
printf("\nIP\tmac");
for(i=0;i<3;i++){
printf("\n%s\t%s",in[i].ip,in[i].mac);
}
sockfd=socket(AF_INET,SOCK_DGRAM,0);
if(sockfd!=-1) printf("Socket created");
servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(1377);
servaddr.sin_addr.s_addr=INADDR_ANY;
len=sizeof(servaddr);
b=bind(sockfd,(struct sockaddr*)&servaddr,sizeof(servaddr));
if(b<0) printf("Error in binding");
bzero(ip,sizeof(ip));
recvfrom(sockfd,ip,sizeof(ip),0,(struct sockaddr*)&servaddr,&len);
bzero(temp,sizeof(temp));
for(i=0;i<strlen(ip)-1;i++)
{ temp[i]=ip[i];
}
temp[i]='\0';
bzero(mac,sizeof(mac));
printf("\n Received IP is %s",temp);
for(i=0;i<3;i++)
{
if((strcmp(temp,in[i].ip))==0){
strcpy(mac,in[i].mac);
break;
}
}
printf("\n MAC address is %s",mac);
sendto(sockfd,mac,sizeof(mac),0,(struct sockaddr*)&servaddr,len);
bzero(mac,sizeof(mac));
recvfrom(sockfd,mac,sizeof(mac),0,(struct sockaddr*)&servaddr,&len);
printf("\n Received Mac address %s",mac);
bzero(temp,sizeof(temp));
for(i=0;i<strlen(mac)-1;i++)
temp[i]=mac[i];
temp[i]='\0';
bzero(ip,sizeof(ip));
printf("Received mac is %s",temp);
for(i=0;i<3;i++)
{
44
if((strcmp(temp,in[i].mac))==0){
strcpy(ip,in[i].ip);
break;
}
}
printf("\n IP Address:%s",ip);
sendto(sockfd,ip,sizeof(ip),0,(struct sockaddr*)&servaddr,len);
return 0;
}
Output:
[sudha@ritlinux ~]$ cc arpserver.c -o ars
[sudha@ritlinux ~]$ ./ars
IP mac
10.1.1.8 44:dd:22:11:33
127.0.0.1 33:aa:fe:4e:2d
10.1.8.5 23:a3:5d:33:9dSocket created
Received IP is 127.0.0.1
MAC address is 33:aa:fe:4e:2d
Received Mac address 23:a3:5d:33:9d
Received mac is 23:a3:5d:33:9d
ARP Client:
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<stdlib.h>
int main(){
int sid,bd,lis,acpt,i,j,status,length;
struct sockaddr_in sin;
char ip[30],mac[30];
socklen_t len;
sid=socket(PF_INET,SOCK_DGRAM,0);
if(sid<0){
printf("\n Error in creating socket");
exit(-1);
}
printf("\n Socket created successfully");
memset(&sin,0,sizeof(sin));
sin.sin_family=AF_INET;
sin.sin_port=htons(1377);
sin.sin_addr.s_addr=htonl(INADDR_ANY);
45
printf("\n ARP stimulation");
printf("\n Enter IP address:");
fgets(ip,sizeof(ip),stdin);
sendto(sid,ip,sizeof(ip),0,(struct sockaddr*)&sin,sizeof(sin));
length=sizeof(sin);
recvfrom(sid,mac,sizeof(mac),0,(struct sockaddr*)&sin,&len);
printf("\n MAC address:%s",mac);
printf("\n RARP simulation");
printf("\n Enter MAC address:");
bzero(mac,sizeof(mac));
fgets(mac,sizeof(mac),stdin);
sendto(sid,mac,sizeof(mac),0,(struct sockaddr*)&sin,len);
recvfrom(sid,ip,sizeof(ip),0,(struct sockaddr*)&sin,&len);
printf("\n IP address is:%s,ip");
return 0;
}
Socket created successfully
ARP stimulation
Enter IP address:127.0.0.1
MAC address:33:aa:fe:4e:2d
RARP simulation
Enter MAC address:23:a3:5d:33:9d
IP address is:10.1.8.5,ip[sudha@ritlinux ~]$
Result:
Thus the program to implement ARP/RARP was done and output was verified
Viva Questions:
1. Expand ARP and RARP.
2. Define unicast ,broadcast and multicast
3. ARP request is broadcast or unicast why?
4. ARP respond is unicast why?
5. Explain Physical address and Logical address.
6. Differnece between ARP and RARP
7. Define term Gateway
46
Ex.No: 7a
STUDY OF NETWORK SIMULATOR (NS)
Date:
Aim:
To study about Network Simulator-2 and its uses
Introduction to NS-2:
Widely known as NS2, is simply an event driven simulation tool.
Useful in studying the dynamic nature of communication networks.
Simulation of wired as well as wireless network functions and protocols (e.g., routing
algorithms, TCP, UDP) can be done using NS2.
In general, NS2 provides users with a way of specifying such network protocols and
simulating their corresponding behaviors
Basic Architecture of NS2
Tcl scripting
• Tcl is a general purpose scripting language. [Interpreter]
• Tcl runs on most of the platforms such as Unix, Windows, and Mac.
• The strength of Tcl is its simplicity.
• It is not necessary to declare a data type for variable prior to the usage.
Basics of TCL
Syntax: command arg1 arg2 arg3
Hello World!
puts stdout{Hello, World!}
Hello, World!
Variables Command Substitution
set a 5 set len [string length foobar]
set b $a set len [expr [string length foobar] + 9]
47
Simple Arithmetic
expr 7.2 / 4
Procedures
proc Diag {a b} {
set c [expr sqrt($a * $a + $b * $b)]
return $c }
puts ―Diagonal of a 3, 4 right triangle is [Diag 3 4]‖
Output: Diagonal of a 3, 4 right triangle is 5.0
Loops
while{$i < $n} { for {set i 0} {$i < $n} {incr i} {
... ...
} }
Wired TCL Script Components
Create the event scheduler
Open new files & turn on the tracing
Create the nodes
Setup the links
Configure the traffic type (e.g., TCP, UDP, etc) Set the
time of traffic generation (e.g., CBR, FTP) Terminate
the simulation
NS Simulator Preliminaries.
1. Initialization and termination aspects of the ns simulator.
2. Definition of network nodes, links, queues and topology.
3. Definition of agents and of applications.
4. The nam visualization tool.
5. Tracing and random variables.
Which is thus the first line in the tcl script? This line declares a new variable as using the set
command, you can call this variable as you wish, In general people declares it as ns because
48
it is an instance of the Simulator class, so an object the code[new Simulator] is indeed the
installation of the class Simulator using the reserved word new.
In order to have output files with data on the simulation (trace files) or files used for
visualization (nam files), we need to create the files using ―open command:
The word proc declares a procedure in this case called finish and without arguments. The word
global is used to tell that we are using variables declared outside the procedure. The simulator
method ―flush-trace” will dump the traces on the respective files. The tcl command ―close”
closes the trace files defined before and exec executes the nam program for visualization. The
command exit will ends the application and return the number 0 as status to the system. Zero
is the default for a clean exit. Other values can be used to say that is a exit because something
49
fails.
At the end of ns program we should call the procedure ―finish‖ and specify at what
time the termination should occur. For example,
$ns at 125.0 “finish”
will be used to call ―finish‖ at time 125sec.Indeed,the at method of the simulator allows us to
schedule events explicitly.
The simulation can then begin using the command
$ns run
The node is created which is printed by the variable n0. When we shall refer to that node in
the script we shall thus write $n0.
Once we define several nodes, we can define the links that connect them. An example of a
definition of a link is:
Which means that $n0 and $n2 are connected using a bi-directional link that has 10ms of
propagation delay and a capacity of 10Mb per sec for each direction.
To define a directional link instead of a bi-directional one, we should replace ―duplex-
link‖ by ―simplex-link‖.
In NS, an output queue of a node is implemented as a part of each link whose input is that node.
The definition of the link then includes the way to handle overflow at that queue. In our case,
if the buffer capacity of the output queue is exceeded then the last packet to arrive is dropped.
Many alternative options exist, such as the RED (Random Early Discard)
mechanism, the FQ (Fair Queuing), the DRR (Deficit Round Robin), the stochastic Fair
Queuing (SFQ) and the CBQ (which including a priority and a round-robin scheduler).
In ns, an output queue of a node is implemented as a part of each link whose input is that
node. We should also define the buffer capacity of the queue related to each link. An
50
example would be:
The command $ns attach-agent $n0 $tcp defines the source node of the tcp connection.
The command
set sink [new Agent /TCPSink
Defines the behavior of the destination node of TCP and assigns to it a pointer called sink.
51
#setup a CBR over UDP connection
set cbr [new Application/Traffic/CBR]
When we have several flows, we may wish to distinguish them so that we can identify them with
different colors in the visualization part. This is done by the command $tcp set fid_ 1 that
assigns to the TCP connection a flow identification of ―1‖.We shall later give the flow
identification of ―2‖ to the UDP connection.
52
Scheduling Events
NS is a discrete event based simulation. The tcp script defines when event should occur. The
initializing command set ns [new Simulator] creates an event scheduler, and events are then
scheduled using the format:
$ns at <time> <event>
The scheduler is started when running ns that is through the command $ns run.
The beginning and end of the FTP and CBR application can be done through the following
command
$ns at 0.1 “$cbr start”
1. The first field is the event type. It is given by one of four possible symbols r, +, -, d which
correspond respectively to receive (at the output of the link), enqueued, dequeued and dropped.
2. The second field gives the time at which the event occurs.
3. Gives the input node of the link at which the event occurs.
4. Gives the output node of the link at which the event occurs.
5. Gives the packet type (eg CBR or TCP)
6. Gives the packet size
7. Some flags
8. This is the flow id (fid) of IPv6 that a user can set for each flow at the input OTcl script
one can further use this field for analysis purposes; it is also used when specifying stream color
for the NAM display.
53
9. This is the source address given in the form of ―node.port‖.
10. This is the destination address, given in the same form.
11. This is the network layer protocol’s packet sequence number. Even though UDP
implementations in a real network do not use sequence number, ns keeps track of UDP packet sequence
number for analysis purposes
12. The last field shows the unique id of the packet.
Result:
Thus the introduction of Network Simulator was studied.
54
Ex.No: 7 b
SIMULATION OF CONGESTION CONTROL ALGORITHM
Date:
AIM:
To simulate a link failure and observe the congestion control algorithm using NS2.
ALGORITHM:
1. Create a simulation object
2. Set routing protocol to routing
3. Trace packets and all links onto NAM trace and to trace file
4. Create right nodes
5. Describe their layout topology as octagon
6. Add a sink agent to node
7. Connect source and sink.
PROGRAM:
set ns [new Simulator]
set nr [open thro_red.tr w]
$ns trace-all $nr
set nf [open thro.nam w]
$ns namtrace-all $nf
proc finish { } {
global ns nr nf
$ns flush-trace
close $nf
close $nr
exec nam thro.nam &
exit 0 }.
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
set n6 [$ns node]
set n7 [$ns node]
$ns duplex-link $n0 $n3 1Mb 10ms RED
$ns duplex-link $n1 $n3 1Mb 10ms RED
$ns duplex-link $n2 $n3 1Mb 10ms RED
55
$ns duplex-link $n3 $n4 1Mb 10ms RED
$ns duplex-link $n4 $n5 1Mb 10ms RED
$ns duplex-link $n4 $n6 1Mb 10ms RED
$ns duplex-link $n4 $n7 1Mb 10ms RED
$ns duplex-link-op $n0 $n3 orient right-up
$ns duplex-link-op $n3 $n4 orient middle
$ns duplex-link-op $n2 $n3 orient right-down
$ns duplex-link-op $n4 $n5 orient right-up
$ns duplex-link-op $n4 $n7 orient right-down
$ns duplex-link-op $n1 $n3 orient right
$ns duplex-link-op $n6 $n4 orient left
set udp0 [new Agent/UDP]
$ns attach-agent $n2 $udp0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0
set null0 [new Agent/Null]
$ns attach-agent $n5 $null0
$ns connect $udp0 $null0
set udp1 [new Agent/UDP]
$ns attach-agent $n1 $udp1
set cbr1 [new Application/Traffic/CBR]
$cbr1 set packetSize_ 500
$cbr1 set interval_ 0.005
$cbr1 attach-agent $udp1
set null0 [new Agent/Null]
$ns attach-agent $n6 $null0
$ns connect $udp1 $null0
set udp2 [new Agent/UDP]
$ns attach-agent $n0 $udp2
set cbr2 [new Application/Traffic/CBR]
$cbr2 set packet size_ 500
$cbr2 set interval_ 0.005
$cbr2 attach-agent $udp2
set null0 [new Agent/Null]
$ns attach-agent $n7 $null0
56
$ns connect $udp2 $null0
$udp0 set fid_ 1
$udp1 set fid_ 2
$udp2 set fid_ 3
$ns color 1 Red
$ns color 2 Green
$ns color 2 Blue
$ns at 0.1 "$cbr0 start"
$ns at 0.2 "$cbr1 start"
$ns at 0.5 "$cbr2 start"
$ns at 4.0 "$cbr2 stop"
$ns at 4.2 "$cbr1 stop"
$ns at 4.5 "$cbr0 stop"
$ns at 5.0 "finish"
$ns run
Viva Questions:
1. Write the features of NS2.
2. What is CBR in NS2
3. List the different types of agents used in NS2
4. Differnce beteen trace file and NAM file .
5. What is meant by congestion?
6. Why the congestion occurs in network?
7. What are the types of congestion control algorithms?
8. Difference between congestion control and flow control?
9. What is the concepts used by TCP to control the congestion
57
Ex.No: 8 STUDY OF TCP/UDP PERFORMANCE USING SIMULATION TOOL
Date:
TCP implements a window based flow control mechanism, a window based protocol means that
the so called current window size defines a strict upper bound on the amount of unacknowledged data
that can be in transit between a given sender receiver pair. Originally TCP’s flow control was governed
simply by the maximum allowed window size advertised by the receiver and the policy that allowed the
sender to send new packets only after receiving the acknowledgement for the previous packet. After the
occurrence of the so called congestion collapse in the Internet in the late 80’s it was realised, however,
that special congestion control algorithms would be required to prevent the TCP senders from
overrunning the resources of the network. In 1988, Tahoe TCP was released including three congestion
control algorithms: slow start, congestion avoidance and fast retransmit. In 1990 Reno TCP, providing
one more algorithm called fast recovery, was released. Besides the receiver’s advertised window, awnd,
TCP’s congestion control introduced two new variables for the connection: the congestion window,
cwnd, and the slowstart threshold, ssthresh. The window size of the sender, w, was defined to be w =
min(cwnd, awnd), instead of being equal to awnd. The congestion window can be thought of as being a
counterpart to advertised window. Whereas awnd is used to prevent the sender from overrunning the
resources of the receiver, the purpose of cwnd is to prevent the sender from sending more data than the
network can accommodate in the current load conditions.
Timeouts: Associated with each packet is a timer. If it expires, timeout occurs, and the packet is
retransmitted. The value of the timer, denoted by RTO, should ideally be of the order of an RTT.
However, as the value of RTT is not known in practice, it is measured by the TCP connection by using,
e.g, the so called Jacobson/Karels algorithm. In this exercise, you will also need to measure the value of
RTO, explained later in chapter 3.7. Duplicate ACKs: If a packet has been lost, the receiver keeps sending
acknowledgements but does not modify the sequence number field in the ACK packets. When the sender
observes several ACKs acknowledging the same packet, it concludes that a packet has been lost.
58
in the network. At this point, the connection goes to congestion avoidance phase where the value of cwnd
is increased less aggressively with the pattern cwnd = cwnd + 1/cwnd, implying linear instead of
exponential growth. This linear increase will continue until a packet loss is detected.
This can be done using following syntax:
set <object name> [new Simulator]
One example for the above specified syntax:
set ns [new Simulator]
We can use routing or we can omit this activity under
Syntax: $<object>rtproto <protocol>
Eg: $ns rtproto DV
Syntax:
Set <file instance> [open <filename>.tr w] Eg: set f [open out.tr w]This creates the file with file name
and open that file in write mode. After opening the file, we need to set our simulation to store all events
to that log file in .tr format. This can be done by:
$ns trace-all $f
Thus, we have set all settings for trace file where entry to file is made when simulator is in run mode.
Once the task of trace file generation is over, we move forward for generation of nam file to display the
graphical format of events occurring in trace file. This can be done as follows:
First create object for nam file and then attach that object to operation.
eg. set nf [open out.nam w]
$ns namtrace-all $nf
Now next step for us would be the generation of topology. Topology consists of nodes and edges.
Talking network point of view, we generate senders and receivers and intermediate gateways and then
we set TCP connections between nodes.
Here we named G and R as gateway and receiver respectively. Till we do not set the parameters and link
specifications between the nodes, each sender, receiver or intermediate nodes are treated as same i.e a
simple node or terminal. We can see that definition has no difference between them whether a sender,
receiver or gateway.
As there are many senders sending to single receiver in our topology, we prefer to distinguish between
the traffic flows from each sender to single receiver.
In the congestion situation, our router would try to accommodate maximum of the packets limited to
size of queue defined. To define this, we can use following code.
We can start monitoring queue at particular time. This can be done using following code.
$ns duplex-link-op $n1 $n5 queuePos 0.5.
We can use this code for each connection between nodes with gateway. Next job for us would be creation
of traffic. Before execution start, even if we have topology ready, parameters determined, execution of
simulation is effective only if we generate test traffic. Even the analysis can be done only after the traffic
is generated and executed.
Traffic can be of two types: Connection oriented and Connectionless. To create connection oriented
traffic, we need to take help of TCP and SINK agents available with NS2. And to create connectionless
traffic, we need UDP and NULL agents. This can be done between each sender and receiver using
following code.
In the above written code, we set TCP connection on source and attach it to sender node. Then we created
TCP Sink to receiver. We connected the TCP and TCPSink. Also, we set window size equal to 8. The
set up flow of traffic between 2 nodes have been given id 1 in last line. There after we created FTP
over TCP connection. Not only data packets also files can be transferred over the same connection
between nodes n0 and n7.
Then we created UDP connection between nodes n4 and n7.We generated CBR (constant bit rate) traffic
over UDP connection with the packet size equal to 100 and rate set to 1mb with no randomization. Same
code would be implemented between other nodes with options available for agents are TCP, TCPSink,
UDP, Null, CBR, etc. Connection between these nodes gets completed only after connecting these nodes.
We are done with all other task. Moving towards end of the definition of tcl file.
Once the metrics have been chosen, one goes for evaluation by subjecting the network under one could
make step by step increments in bandwidth of the links, which in turn improve the throughput. However,
the throughput might get saturated beyond the certain point. That is, further increase improve throughput.
Thus, the optimum determined. It might not be always possible rather feas from a network due to various
factors like and topology complexity, compatibility of available network components. In such cases one
would like to obtain optimum performance by balancing different factors which we call trade-off
between available inevitable odd situations.
61
For example, increments in bandwidth of the links, which in the throughput. However, the throughput
might get saturated yond the certain point. That is, further increase in bandwidth would not improve
throughput. Thus, the optimum value of bandwidth has been It might not be always possible rather
feasible to obtain best performance from a network due to various factors like high cost equipment’s,
network compatibility of available network components. In one would like to obtain optimum
performance by balancing different factors which we call trade off between available benefit
Some of the parameters that can be used for comparative study of performance of the network are: link
bandwidth, propagation delay, node queue type.
For example:
In ns2 we do create a link by using this code: 1 $ns simplex-link $n2 $n6 0.3Mb 100ms DropTail 2 $ns
duplex-link $n3 $n6 0.3Mb 100ms DropTail In this code there could be three parameters namely
bandwidth, propagation delay and queue type.
We can vary these parameters and could possibly obtain different throughputs. From there we can
determine the conditions that provide higher throughput values. That is, we can alter different parameters
and study their effects on one or more performance metrics and thereby filter out the combination of
parameters that gives best performance.
Result:
Thus the TCP/UDP performance using simulation tool, NS2 (Network Simulator 2) has been
studied.
Viva Questions
1. How the performance can be measured and evaluated
2. Write the parameters used to measure networks performance
3. List the metrics that influence the performance of computer networks
4. Name the factors that affect the reliability of a network.
5. How is RTT computed?
6. What is the function of transmission timer?
7. What are the approaches used to provide a range of Quality of service.
8. Write the purpose of these timers in TCP:
9. How is flow control and error control in TCP?
62
Ex.No:9 a. SIMULATION OF DISTANCE VECTOR
Date:
AIM:
To simulate and study the Distance Vector routing algorithm using simulation
Explanation
Distance Vector Routing is one of the routing algorithms in a Wide Area Network for computing
shortest path between source and destination. The Router is one main devices used in a wide area
network. The main task of the router is Routing. It forms the routing table and delivers the packets
depending upon the routes in the table-either directly or via an intermediate devices. Each router initially
has information about its all neighbours. Then this information will be shared among nodes.
ALGORITHM:
1. Create a simulator object
2. Define different colors for different data flows
3. Open a nam trace file and define finish procedure then close the trace file, and execute nam on trace
file.
4. Create n number of nodes using for loop
5. Create duplex links between the nodes
6. Setup UDP Connection between n(0) and n(5)
7. Setup another UDP connection between n(1) and n(5)
8. Apply CBR Traffic over both UDP connections
9. Choose distance vector routing protocol to transmit data from sender to receiver.
10. Schedule events and run the program.
PROGRAM:
set ns [new Simulator]
set nr [open thro.tr w]
$ns trace-all $nr
set nf [open thro.nam w]
$ns namtrace-all $nf
proc finish { } {
global ns nr nf
$ns flush-trace
close $nf
close $nr
exec nam thro.nam &
exit 0
}
for { set i 0 } { $i < 12} { incr i 1 } {
set n($i) [$ns node]}
for {set i 0} {$i < 8} {incr i} {
$ns duplex-link $n($i) $n([expr $i+1]) 1Mb 10ms DropTail }
$ns duplex-link $n(0) $n(8) 1Mb 10ms DropTail
$ns duplex-link $n(1) $n(10) 1Mb 10ms DropTail
$ns duplex-link $n(0) $n(9) 1Mb 10ms DropTail
$ns duplex-link $n(9) $n(11) 1Mb 10ms DropTail
$ns duplex-link $n(10) $n(11) 1Mb 10ms DropTail
$ns duplex-link $n(11) $n(5) 1Mb 10ms DropTail
set udp0 [new Agent/UDP]
$ns attach-agent $n(0) $udp0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
63
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0
set null0 [new Agent/Null]
$ns attach-agent $n(5) $null0
$ns connect $udp0 $null0
set udp1 [new Agent/UDP]
$ns attach-agent $n(1) $udp1
set cbr1 [new Application/Traffic/CBR]
$cbr1 set packetSize_ 500
$cbr1 set interval_ 0.005
$cbr1 attach-agent $udp1
set null0 [new Agent/Null]
$ns attach-agent $n(5) $null0
$ns connect $udp1 $null0
$ns rtproto DV
$ns rtmodel-at 10.0 down $n(11) $n(5)
$ns rtmodel-at 15.0 down $n(7) $n(6)
$ns rtmodel-at 30.0 up $n(11) $n(5)
$ns rtmodel-at 20.0 up $n(7) $n(6)
$udp0 set fid_ 1
$udp1 set fid_ 2
$ns color 1 Red
$ns color 2 Green
$ns at 1.0 "$cbr0 start"
$ns at 2.0 "$cbr1 start"
$ns at 45 "finish"
$ns run
Output:
RESULT:
Thus the Distance vector Routing Algorithm was Simulated and studied.
64
Ex.No: 9 b SIMULATION OF LINK STATE ROUTING
Date:
AIM:
To simulate and study the link state routing algorithm using simulation.
Explanation
In link state routing, each router shares its knowledge of its neighborhood with every other router
in the internet work. (i) Knowledge about Neighborhood: Instead of sending its entire routing table a
router sends info about its neighborhood only. (ii) To all Routers: each router sends this information to
every other router on the internet work not just to its neighbor .It does so by a process called flooding.
(iii)Information sharing when there is a change: Each router sends out information about the neighbors
when there is change.
The Dijkstra algorithm follows four steps to discover what is called the shortest path tree
(routing table) for each router:The algorithm begins to build the tree by identifying its roots. The root
router’s trees the router itself. The algorithm then attaches all nodes that can be reached from the root.
The algorithm compares the tree’s temporary arcs and identifies the arc with the lowest cumulative cost.
This arc and the node to which it connects are now a permanent part of the shortest path tree. The
algorithm examines the database and identifies every node that can be reached from its chosen node.
These nodes and their arcs are added temporarily to the tree.
The last two steps are repeated until every node in the network has become a permanent part of
the tree.
ALGORITHM:
1. Create a simulator object
2. Define different colors for different data flows
3. Open a nam trace file and define finish procedure then close the trace file, and execute nam on trace
file.
4. Create n number of nodes using for loop
5. Create duplex links between the nodes
6. Setup UDP Connection between n(0) and n(5)
7. Setup another UDP connection between n(1) and n(5)
8. Apply CBR Traffic over both UDP connections
9. Choose Link state routing protocol to transmit data from sender to receiver.
10. Schedule events and run the program.
PROGRAM:
set ns [new Simulator]
set nr [open thro.tr w]
$ns trace-all $nr
set nf [open thro.nam w]
$ns namtrace-all $nf
proc finish { } {
global ns nr nf
$ns flush-trace
close $nf
close $nr
exec nam thro.nam &
exit 0
}
for { set i 0 } { $i < 12} { incr i 1 } {
set n($i) [$ns node]}
for {set i 0} {$i < 8} {incr i} {
65
$ns duplex-link $n($i) $n([expr $i+1]) 1Mb 10ms DropTail }
$ns duplex-link $n(0) $n(8) 1Mb 10ms DropTail
$ns duplex-link $n(1) $n(10) 1Mb 10ms DropTail
$ns duplex-link $n(0) $n(9) 1Mb 10ms DropTail
$ns duplex-link $n(9) $n(11) 1Mb 10ms DropTail
$ns duplex-link $n(10) $n(11) 1Mb 10ms DropTail
$ns duplex-link $n(11) $n(5) 1Mb 10ms DropTail
set udp0 [new Agent/UDP]
$ns attach-agent $n(0) $udp0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0
set null0 [new Agent/Null]
$ns attach-agent $n(5) $null0
$ns connect $udp0 $null0
set udp1 [new Agent/UDP]
$ns attach-agent $n(1) $udp1
set cbr1 [new Application/Traffic/CBR]
$cbr1 set packetSize_ 500
$cbr1 set interval_ 0.005
$cbr1 attach-agent $udp1
set null0 [new Agent/Null]
$ns attach-agent $n(5) $null0
$ns connect $udp1 $null0
$ns rtproto LS
$ns rtmodel-at 10.0 down $n(11) $n(5)
$ns rtmodel-at 15.0 down $n(7) $n(6)
$ns rtmodel-at 30.0 up $n(11) $n(5)
$ns rtmodel-at 20.0 up $n(7) $n(6)
$udp0 set fid_ 1
$udp1 set fid_ 2
$ns color 1 Red
$ns color 2 Green
$ns at 1.0 "$cbr0 start"
$ns at 2.0 "$cbr1 start"
$ns at 45 "finish"
$ns run
Output:
66
RESULT:
Thus the Link State Routing Algorithm was Simulated and studied
Viva Questions:
67
Ex.No: 10
SIMULATION OF ERROR CORRECTION CODE (LIKE CRC)
Date:
AIM:
To implement error detection and error correction techniques (CRC)
Explanation:
Unlike checksum scheme, which is based on addition, CRC is based on binary division.
In CRC, a sequence of redundant bits, called cyclic redundancy check bits, are appended to
the end of data unit so that the resulting data unit becomes exactly divisible by a second,
predetermined binary number.
At the destination, the incoming data unit is divided by the same number. If at this step there
is no remainder, the data unit is assumed to be correct and is therefore accepted.
A remainder indicates that the data unit has been damaged in transit and therefore
must be rejected.
68
ALGORITHM:
1. Open Turbo c ftware and type the program for error detection
2. Get the input in the form of bits.
3. Append 16 zeros as redundancy bits.
4. Divide the appended data using a divisor polynomial.
5. The resulting data should be transmitted to the receiver.
6. At the receiver the received data is entered.
7. The same process is repeated at the receiver.
8. If the remainder is zero there is no error otherwise there is some error in the received bits
9. Run the program.
PROGRAM
#include<stdio.h>
char m[50],g[50],r[50],q[50],temp[50];
void caltrans(int);
void crc(int);
void calram();
void shiftl();
int main()
{
int n,i=0;
char ch,flag=0;
printf("Enter the frame bits:");
while((ch=getc(stdin))!='\n')
m[i++]=ch;
n=i;
for(i=0;i<16;i++)
m[n++]='0';
m[n]='\0';
printf("Message after appending 16 zeros:%s",m);
for(i=0;i<=16;i++)
g[i]='0';
g[0]=g[4]=g[11]=g[16]='1';g[17]='\0';
printf("\ngenerator:%s\n",g);
69
crc(n);
printf("\n\nquotient:%s",q);
caltrans(n);
printf("\ntransmitted frame:%s",m);
printf("\nEnter transmitted frame:");
scanf("\n%s",m);
printf("CRC checking\n");
crc(n);
printf("\n\nlast remainder:%s",r);
for(i=0;i<16;i++)
if(r[i]!='0')
flag=1;
else
continue;
if(flag==1)
printf("Error during transmission");
else
printf("\n\nReceived freme is correct");
}
void crc(int n)
{
int i,j;
for(i=0;i<n;i++)
temp[i]=m[i];
for(i=0;i<16;i++)
r[i]=m[i];
printf("\nintermediate remainder\n");
for(i=0;i<n-16;i++)
{
if(r[0]=='1')
{
q[i]='1';
calram();
}
else
{
q[i]='0';
shiftl();
}
r[16]=m[17+i];
r[17]='\0';
printf("\nremainder %d:%s",i+1,r);
for(j=0;j<=17;j++)
temp[j]=r[j];
}
q[n-16]='\0';
}
void calram()
{
int i,j;
for(i=1;i<=16;i++)
r[i-1]=((int)temp[i]-48)^((int)g[i]-48)+48;
}
void shiftl()
{
70
int i;
for(i=1;i<=16;i++)
r[i-1]=r[i];
}
void caltrans(int n)
{
int i,k=0;
for(i=n-16;i<n;i++)
m[i]=((int)m[i]-48)^((int)r[k++]-48)+48;
m[i]='\0';
}
OUTPUT:
Enter the Frame Bits:
1011
The msg after appending 16 zeros:
10110000000000000000
The Transmitted frame is:10111011000101101011
Enter the transmitted Frame
10111011000101101011
Received msg:10111011000101101011
The Remainder is:0000000000000000
Received frame is correct
RESULT:
Thus the simulation of error correction code (like CRC) was implemented
Viva Questions:
71
Additional Exp SIMULATION OF STOP-AND-WAIT & SLIDING WINDOW
Date: PROTOCOL
Mini Project
AIM:
To Simulate and to study stop and Wait protocol
Theory:
Stop and Wait is a reliable transmission flow control protocol. This protocol works only in
Connection Oriented (Point to Point) Transmission. The Source node has window size of ONE. After
transmission of a frame the transmitting (Source) node waits for an Acknowledgement from the
destination node. If the transmitted frame reaches the destination without error, the destination transmits
a positive acknowledgement. If the transmitted frame reaches the destination with error, the receiver
destination does not transmit an acknowledgement. If the transmitter receives a positive
acknowledgement it transmits the next frame if any. Else if its acknowledgement receive timer expires,
it retransmits the same frame.
1. Start with the window size of 1 from the transmitting (Source) node
2. After transmission of a frame the transmitting (Source) node waits for a reply (Acknowledgement)
from the receiving (Destination) node.
3. If the transmitted frame reaches the receiver (Destination) without error, the receiver (Destination)
transmits a Positive Acknowledgement.
4. If the transmitted frame reaches the receiver (Destination) with error, the receiver (Destination) do
not transmit acknowledgement.
5. If the transmitter receives a positive acknowledgement it transmits the next frame if any. Else if the
transmission timer expires, it retransmits the same frame again.
6. If the transmitted acknowledgment reaches the Transmitter (Destination) without error, the
Transmitter (Destination) transmits the next frame if any.
7. If the transmitted frame reaches the Transmitter (Destination) with error, the Transmitter
(Destination) transmits the same frame.
8. This concept of the Transmitting (Source) node waiting after transmission for a reply from the
receiver is known as STOP and WAIT.
ALGORITHM:
1. Create a simulator object
2. Define different colors for different data flows
3. Open a nam trace file and define finish procedure then close the trace file, and execute nam on trace
72
file.
4. Create two nodes that forms a network numbered 0 and 1
5. Create duplex links between the nodes to form a STAR Topology
6. Setup TCP Connection between n(1) and n(3)
7. Apply CBR Traffic over TCP
8. Schedule events and run the program.
THEORY:
A sliding window protocol is a feature of packet-based data transmission protocols. Sliding
window protocols are used where reliable in-order delivery of packets is required, such as in the Data
Link Layer (OSI model) as well as in the Transmission Control Protocol (TCP). Conceptually, each
portion of the transmission (packets in most data link layers, but bytes in TCP) is assigned a unique
consecutive sequence number, and the receiver uses the numbers to place received packets in the correct
order, discarding duplicate packets and identifying missing ones. The problem with this is that there is
no limit on the size of the sequence number that can be required. By placing limits on the number of
packets that can be transmitted or received at any given time, a sliding window protocol allows an
unlimited number of packets to be communicated using fixed-size sequence numbers. The term
"window" on the transmitter side represents the logical boundary of the total number of packets yet to
be acknowledged by the receiver.
The receiver informs the transmitter in each acknowledgment packet the current maximum
receiver buffer size (window boundary). The TCP header uses a 16 bit field to report the receive window
size to the sender. Therefore, the largest window that can be used is 216 = 64 kilobytes. In slow-start
mode, the transmitter starts with low packet count and increases the number of packets in each
74
transmission after receiving acknowledgment packets from receiver. For every ack packet received, the
window slides by one packet (logically) to transmit one new packet. When the window threshold is
reached, the transmitter sends one packet for one ack packet received. If the window limit is 10 packets
then in slow start mode the transmitter may start transmitting one packet followed by two packets (before
transmitting two packets, one packet ack has to be received), followed by three packets and so on until
10 packets. But after reaching 10 packets, further transmissions are restricted to one packet transmitted
for one ack packet received. In a simulation this appears as if the window is moving by one packet
distance for every ack packet received. On the receiver side also the window moves one packet for every
packet received. The sliding window method ensures that traffic congestion on the network is avoided.
The application layer will still be offering data for transmission to TCP without worrying about the
network traffic congestion issues as the TCP on sender and receiver side implement sliding windows of
packet buffer.
The window size may vary dynamically depending on network traffic. For the highest possible
throughput, it is important that the transmitter is not forced to stop sending by the sliding window
protocol earlier than one round-trip delay time (RTT). The limit on the amount of data that it can send
before stopping to wait for an acknowledgment should be larger than the bandwidth-delay product of
the communications link. If it is not, the protocol will limit the effective bandwidth of the link.
Output:
76
SIMULATION OF STOP-AND-WAIT PROTOCOL USING LAN TRAINER KIT
Select all other settings like; frame size, inter frame delay, & bit error rate
77
Now choose the parameters
we can see a frame status with blue color and Acknowledge status with red color
We can stop transfer of file by removing check from Ack. Send enable button on receiver side
here green colour represents frame received and yellow colour represents acknowledgement
sent.
78
Observe on sender side same status waiting for Acknowledgement
To start transfer of file continuously check on Ack. Send enable button on receiver side
79
We can also see the detail timings of each packet.
RESULT:
Thus the Stop and Wait protocol and Sliding window Protocols are Simulated and studied
Viva Questions:
1. Define piggybacking
2. Expand ARQ
3. Write the concepts of ARQ protocol
4. What is stop and wait protocol
5. Differnence between stop and wait and sliding window protocol
6. Write the use of timer in ARQ
7. Compare the selective repaeat and Go back N protocol
8. Which protocol increase the congestion in network?why
80
BESIDES UNIVERSITY SYLLABUS
REFERENCES
1. https://www.thegeekstuff.com/2011/12/c-socket-programming/
2. https://microchipdeveloper.com/tcpip:client-server-programming-model
3. https://www.geeksforgeeks.org/tcp-server-client-implementation-in-c/
4. https://aticleworld.com/socket-programming-in-c-using-tcpip/
81