Master Copy of Nework Lab 2021 Regulation Lab Manual

Download as pdf or txt
Download as pdf or txt
You are on page 1of 89

CS3591 – COMPUTER NETWORK LABORATORY

MASTER RECORD / LAB MANUAL

Department of Computer Science and Engineering


III Year / V Semester CSE

RAMCO INSTITUTE OF TECHNOLOGY


Rajapalayam – 626 117
Tamil Nadu
July 2023
MASTER RECORD / LAB MANUAL

Department of Computer Science and Engineering


III Year / V Semester CSE

RAMCO INSTITUTE OF TECHNOLOGY


Rajapalayam – 626 117
Tamil Nadu
July 2023
VISION AND MISSION

Vision of the Institute


To evolve as an Institute of international repute in offering high-quality technical education, Research
and extension programmes in order to create knowledgeable, professionally competent and skilled
Engineers and Technologists capable of working in multi-disciplinary environment to cater to the
societal needs.

Mission of the Institute


To accomplish its unique vision, the Institute has a far-reaching mission that aims:
 To offer higher education in Engineering and Technology with highest level of quality,
Professionalism and ethical standards
 To equip the students with up-to-date knowledge in cutting-edge technologies, wisdom, creativity
and passion for innovation, and life-long learning skills
 To constantly motivate and involve the students and faculty members in the education process for
continuously improving their performance to achieve excellence.

Vision of the Department

To produce highly competent Electrical and Electronics Engineers with professional skills and a sense
of ethics to meet the demands of technologically advancing society.

Mission of the Department

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

Program Outcomes (POs)


Engineering Graduates will be able to:
 Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals,
and an engineering specialization to the solution of complex engineering problems.
 Problem analysis: Identify, formulate, review research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural sciences,
and engineering sciences.
 Design/development of solutions: Design solutions for complex engineering problems and design
system components or processes that meet the specified needs with appropriate consideration for the
public health and safety, and the cultural, societal, and environmental considerations.
 Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
 Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with
an understanding of the limitations.
 The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.
 Environment and sustainability: Understand the impact of the professional engineering solutions
in societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
 Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms
of the engineering practice.
 Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.

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.

Program Specific Outcomes (PSOs)


After successful completion of the degree, the students will be able to:

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

Course Objectives and Outcomes

CO - Mapping

Study of Header files

Study of Socket Programming and Client – Server model

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

7. a. Study of Network simulator (NS)


b. Simulation of Congestion Control Algorithms using NS
8.
Study of TCP/UDP performance using Simulation tool
9. a. Simulation of Distance Vector
b. Link State Routing algorithm.
10. Simulation of error correction code (like CRC).

Besides University Syllabus

References

vi
CS3591 – NETWORKS LABORATORY
Syllabus 2021 Regulation
LTPC
0042
OBJECTIVES:

 To learn and use network commands.


 To learn socket programming.
 To implement and analyze various network protocols.
 To learn and use simulation tools.
 To use simulation tools to analyze the performance of various network protocols.

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 and Outcomes

Degree, Semester & Branch: V Semester B.E. CSE


Course Code & Title: CS3591 Computer Networks
Name of the Faculty member(s): Mr.R Bala Murugan, AP/CSE

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

S No Name of the Lab Exercises COs


Learn to use commands like tcpdump, netstat, ifconfig, nslookup and
1. CO1
trace route. Capture ping and trace route PDUs using a network
protocol
Write analyzer
a HTTP weband examine.
client program to download a web page using TCP
2. CO1
sockets
Applications using TCP sockets like:
3. a. Echo client and echo server CO2
b. Chat
4.
Simulation of DNS using UDP sockets. CO2

5.
Use a tool like Wireshark to capture packets and examine the packets CO2

6.
Write a code simulating ARP /RARP protocols CO3

7. Study of Network simulator (NS) and Simulation of Congestion Control


CO2
Algorithms using NS
8.
Study of TCP/UDP performance using Simulation tool CO2

9.
Simulation of Distance Vector/ Link State Routing algorithm. CO4

10. Simulation of error correction code (like CRC). CO5

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:

It is a POSIX standard for open system interface.

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:

Defines the data type of socket address structure in unsigned long.

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

2. Primary Socket Calls


 socket() - create a new socket and return its descriptor
 bind() - associate a socket with a port and address
 listen() - establish queue for connection requests
 accept() - accept a connection request
 connect() - initiate a connection to a remote host
 recv() - receive data from a socket descriptor
 send() - send data to a socket descriptor
 close() - “one-way” close of a socket descriptor

3. Network Database Administration functions


 gethostbyname - given a hostname, returns a structure which specifies its DNS name(s) and
IP address(es)
 getservbyname - given service name and protocol, returns a structure which specifies its
name(s) and its port address
 gethostname - returns hostname of local host
 getservbyname, getservbyport, getservent
 getprotobyname, getprotobynumber, getprotobyent
 getnetbyname, getnetbyaddr, getnetent

4. Socket Utility Functions


 ntohs /ntohl - convert short/long from network byte order (big endian to host byte order)
 htons /htonl - convert short/long from host byte order to network byte order
 inet_ntoa /inet_addr - convert 32-bit IP address (network byte order to/from a dotted
decimal string)
 perror () - print error message (based on “ errno”) to stderr
 herror () - print error message for gethostbyname () to stderr (used with DNS)

5. Primary Header Files

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

Connections and Associations


In Socket terms a connections between two processes in called an association. An association
can be abstractly defined as a 5-tuple which specifies the two processes and a method of communication.
For example:

{ protocol, local-addr, local-process, foreign-addr, foreign-process }

A half-association is a single “side” of an association (a 3-tuple)

{ protocol, addr, process }

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.

6 .Basic Socket Calls & Their prototypes


Procedures that implement the Socket API
6.1. The Socket Procedure:
The socket procedure creates a socket and returns an integer descriptor. This descriptor is used
by the application to be passed as an argument to call procedures to transfer data across the network.
 Initialize a socket or create a socket

FORMAT: int sockfd = socket(int family, int type, int protocol)


Returns a socket descriptor if successful;-1 if error
where:
o family stands for addressing family.
 symbolic name Protocol Family
 AF_UNIX intra-host UNIX
 AF_INET TCP/IP[default]
 AF_NS Xerox NS
 AF_DECNET DEC DNA

Its purpose is to specify the method of addressing used by the socket.

o type stands for the type of socket interface to be used.

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 protocol can be UDP, TCP, IP or ICMP.

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

6.2 The Bind Procedure: Bind (Register) a socket to a port address.


The Bind Function binds a socket to a local socket address by adding the local socket address to
an already created socket. When Created a socket has neither a local address nor a remote address. A
Server uses the bind procedure to supply a protocol port number at which the server will wait for contact.
The Prototype is given as
FORMAT: int bind(int sockfd, struct sockaddr *localaddr, int addrlen)
Returns 0 if successful;-1 if error
where:
o sockfd is the same integer returned by the socket call.

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

6.3 The LISTEN Procedure: Indicate readiness to receive connections


The listen function is called only by the server. It creates a passive socket from an unconnected
socket. Before calling the listen function, the socket must already be created and the local socket address
fields set. This function informs the OS that the server is ready to accept the connection through this
socket. To do so, a server calls the listen procedure whose prototype is as follows:

FORMAT: int listen(int sockfd, int queue-size)


Returns 0 if successful;-1 if error
where:
8
o sockfd is the same integer returned by the socket call.

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.

6.4 The Accept Procedure: Accept a connection


The accept function is called by a TCP Server to remove the first connection request from the
corresponding queue. If there are no requests (the queue is empty), the accept function is put to sleep.
The prototype is given as

FORMAT: int accept(int sockfd, struct sockaddr *foreign-address, int addrlen)


Returns a socket descriptor if successful;-1 if error
where:
o sockfd is the same integer returned by the socket 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 Addrlen is the length of the client address.

6.5 The Connect procedure: Request connection to the server


The connect function is used by a process (usually a client) to establish an active connection to a remote
process (server).The prototype is as follows

FORMAT: int connect(int sockfd, struct sockaddr *foreign-address, int addrlen)


Returns 0 if successful;-1 if error
where:
o sockfd is the same integer returned by the socket call.

o foreign-address is the address of foreign (server) process returned by the connect call.

o addrlen is the length of that server address

6.6 Close a socket:


FORMAT: int close(int sockfd)
Returns 0 if successful;-1 if error

where: sockfd is the same integer returned by the socket call.

6.7 Send and/or receive data


 int read(int sockfd, char *buf, unsign int nbytes)
 int write(int sockfd, char *buf, unsign int nbytes)
 readv(sockfd, char *buffer, int addrlen),
 recv(),
 readfrom(),
 send(sockfd, msg, len, flags),
 int recvfrom(int sockfd, char *buf, int nbytes, int flags, struct sockaddr *from, int addrlen)
 int sendto(int sockfd, char *buf, int nbytes, int flags, struct sockaddr *to, int addrlen)
 read() & write () are used for connection oriented Transport
 recvfrom() and sendto() are used for connection less Transport

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

 bufflen is number of bytes to read

 flags can be used to specify options. Always 0 for us.

 *fromaddrptr is address of sockaddr_in structure containing address info of socket that sent
this data. A returned value.

 addresslen is size of address structure. A returned value.

 recvfrom() returns number bytes actually received

Sending Data through send()


To send data over a socket the program will need to make a call to send (); if the socket is non-
blocking the send call should return immediately with the number of bytes that were successfully written
to the sockets output queue. The return from send does not indicate the number of bytes received on the
other end of the connection nor does it indicate how large the TCP packet size is. But if you get a positive
return value on a send call it means the OS has taken responsibility for transmitting that data.

Receiving Data through recv()


To receive data over a socket the program will need to make a call to recv(); if the socket is non-
blocking the recv call should return immediately with the number of bytes that were successfully read
from the sockets input queue. The return from recv does not indicate the number of bytes sent by the
remote host, nor does it indicate how large the tcp packet size was that was read. It is also important to
note that if recv() returns 0 ( zero ) that indicates the remote socket has closed the connection.
Byte Ordering Routines
 Byte ordering routines: convert to/from host 16- and 32-bit integers from/to “network byte order”
o Different computers may store bytes of integer in different order in memory.
o internal representation of 2^{24}
o network byte order is big-endian
o Integer quantities (such as addressing info) should be explicitly converted to/from
network byte order (nbo).
Increasing memory addresses
address A+1 address A

High-order byte Low-order byte Little- endian byte


order

MSB 16-bit value LSB

Big- endian byte order


High-order byte Low-order byte

address A address A+1

Increasing memory addresses

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

Declarations for byte-order transformations


 u_short htons (u_short host_short)
 u_short ntohs (u_short network_short)
 u_long htonl (u_long host_short)
 u_long ntohl (u_long network_short)

Byte Manipulation Functions


In network programming,there is a need to initialize a field, copy the contents of one field to another, or
compare the contents of two fields. Several functions have been defined in the <string.h> header file for
these byte manipulations. They are

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

Return:0 if equal, nonzero if unequal

1. Memset: This function sets a specified number of bytes to a value


2. Memcpy: This function copies the value of one field to another
3. Memcmp This function compares two fields

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:

host name gaia.cs.umass.edu


32-bit address 10000000 01110111 00101000 10111010
dotted decimal 128.119.40.186
 library procedure inet_addr() converts dotted-decimal address string to a 32-bit address
 library procedure gethostbyname() converts textual name to dotted-decimal.

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

Socket addressing: predfined address structures


 specifying socket addresses: certain data structures are predefined as follows:
•Generic Socket Address Structure
•IPv4 Socket Address Structure
• Internet Address Structure

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.

IPv4 Socket Address Structure


struct sockaddr_in /* INET socket addr info */
{
u_char sin_len
short sin_family; /* set to AF_INET */
u_short sin_port; /* 16 bit number, Network Byte Order */
struct in_addr sin_addr; /* 32 bit host address */
char sin_zero[8]; /* not used */
};

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;

Address Conversion Functions


Network software provides functions to transform an IP address from ASCII dotted format to 32-bit
binary format and vice versa. Two of these functions are discussed here

1. inet_aton

FORMAT: int inet_aton(const char *strptr, struct in_addr *addrptr);

Returns: 1 if string was valid, 0 on error


This function transforms an ASCII string that contains up to four segments separated by dots
to a 32-bit binary address in network byte order

2. inet_ntoa

FORMAT: char *inet_ntoa(struct in_addr inaddr);

Returns: pointer to dotted-decimal string


Address Transformation

32-bit Binary address

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

Web link for virtual Lab


https://vlab.amrita.edu/index.php?sub=78&brch=256&sim=1555&cnt=1
The Wireless Sensor Network supported by Amrita Vishwa Vidyapeetham

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

Tracing route to www.l.google.com [209.85.225.104]


over a maximum of 30 hops:
1 <1 ms <1 ms <1 ms 10.1.0.1
2 35 ms 19 ms 29 ms 98.245.140.1
3 11 ms 27 ms 9 ms te-0-3.dnv.comcast.net [68.85.105.201]
... 13 81 ms 76 ms 75 ms 209.85.241.37
14 84 ms 91 ms 87 ms 209.85.248.102
15 76 ms 112 ms 76 ms iy-f104.1e100.net [209.85.225.104]
Trace complete

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

1. List the commands basic network commands.


2. Difference between IPconfig and Ifconfig.
3. What is use of tcpdump and netstat
4. What are the attributes of ping and trace route
5. Mention the use nslookup command.
6. Write the syntax of Netsta with example.
7. Expand DHP,DNS,ARP
8. Which command gives the information about internet servers?

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:

For example, the browser translated the URL http://www.nowhere123.com/doc/index.html into


the following request message:

GET /docs/index.html HTTP/1.1


Host: www.nowhere123.com
Accept: image/gif, image/jpeg, */*
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)
(blank line)

An example of the HTTP response message is as shown:

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.

c. The request cannot be satisfied, the server returns an error message.

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:

1. Expand HTTP URL.


2. Which layer protocol is HTTP?
3. State the use of HTTP protocol
4. Mention the methods of HTTP protocol
5. Write the syntax of HTTP request and HTTP respond
6. What are the four properties of HTTP?
7. Why HTTP is designed as a stateless protocol?
8. What are the four groups of HTTP header?
9. What are categories of web documents?
10. Compare the HTTP and FTP

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.

TCP ECHO 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,bd,lis,acptd,rd,sd;
struct sockaddr_in sin;
char buf[10];
socklen_t len;
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(5110);
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);
26
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);
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);
}

TCP ECHO 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,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(5110);
sin.sin_addr.s_addr=htonl(INADDR_ANY);
con=connect(sid,(struct sockaddr*)&sin,sizeof(sin));
if(con < 0)
{
27
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);
}

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

TCP CHAT 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,acptd,rd,sd;
struct sockaddr_in sin;
char buf[10];
socklen_t len;

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

Domain Name System


The Domain Name System (DNS) is basically a large database which resides on various
computers and it contains the names and IP addresses of various hosts on the internet and various
domains. The Domain Name System is similar to a file system in UNIX or DOS starting with a root.
Branches attach to the root to create a huge set of paths. Each branch in the DNS is called a label. The
domain name system database is divided into sections called zones. The name servers in their respective
zones are responsible for answering queries for their zones. A zone is a subtree of DNS and is
administered separately. There are multiple name servers for a zone. There is usually one primary name
server and one or more secondary name servers. A name server may be authoritative for more than one
zone.
DNS names are assigned through the Internet Registries by the Internet Assigned Number
Authority (IANA). The domain name is a name assigned to a domain. For example, mycollege.edu
represents the domain name of an educational institution. Three main components of DNS
 Resolver

 Name server

 Database of resource records(RRs)

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:

1. What is DNS? What is the Domain Name System responsible for?


2. Define the term domain.
3. Write the three main divisions of the DNS
4. What are the two main categories of DNS messages?
5. Why was there a need for DNS?
6. Define the terms (i) Browser (ii) Hypertext Mark Up language
7. DNS can use the services of UDP or TCP using port 53”. Discuss
8. When can an application make use of UDP?
9. How does a DNS Resolver bootstrap the domain name lookup process?

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

Introduction: Wireshark is an open-source network protocol analysis software program, widely


considered the industry standard. A global organization of network specialists and software
developers supports Wireshark and continues to make updates for new network technologies and
encryption methods. Wireshark is a packet sniffer and analysis tool. It captures network traffic
from ethernet, Bluetooth, wireless (IEEE.802.11), token ring, and frame relay connections, among
others, and stores that data for offline analysis.

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

Capturing data packets on Wireshark


When you open Wireshark, we can see a screen showing a list of all the network connections we
can monitor. We can also have a capture filter field to only capture the network traffic we want
to see.

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

We can select the menu item Capture -> Start.

We use the keystroke Control+E.


During the capture, Wireshark will show you the packets captured in real-time.

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.

Wireshark capture filters

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

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:

1. What is Wireshark, and what is its primary purpose?


2. How does Wireshark capture and display network traffic?
3. What is Wireshark, and what is its primary purpose?
4. How does Wireshark capture and display network traffic?
5. What are the advantages of using TShark over the graphical interface in certain scenarios?

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.

How ARP Works

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

ADDRESS RESOLUTION PROTOCOL

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.

Initialization and Termination of TCL Script in NS-2


An ns simulation starts with the command

set ns [new Simulator]

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:

set tracefile1 [open out.tr w]

$ns trace-all $tracefile1


Open the NAM trace file
set namfile [open out.nam w]
$ns namtrace-all $namfile
The above creates a trace file called ―out.tr‖ and a nam visualization trace file called
―out.nam‖. Within the tcl script, these files are not called explicitly by their names, but
instead by pointers that are declared above and called ―tracefile1‖ and ―namfile‖ respectively.
Remark that they begins with a # symbol. The second line open the file ―out.tr‖ to be used for
writing, declared with the letter ―w‖. The third line uses a simulator method called trace-all that
have as parameter the name of the file where the traces will go.
The last line tells the simulator to record all simulation traces in NAM input format. It also gives
the file name that the trace will be written to later by the command $ns flush-trace. In our case,
this will be the file pointed at by the pointer ―$namfile‖, i.e the file ―out.tr‖.
The termination of the program is done using a ―finish‖ procedure
#Define a „finish‟ procedure
Proc finish { } {
global ns tracefile1 namfile
$ns flush-trace
Close $tracefile1
Close $namfile
Exec nam out.nam & Exit 0
}

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

Definition of a network of links and nodes


The way to define a node is

set n0 [$ns node]

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:

$ns duplex-link $n0 $n2 10Mb 10ms DropTail

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:

#set Queue Size of link (n0-n2) to 20

$ns queue-limit $n0 $n2 20

Agents and Applications


We need to define routing (sources, destinations) the agents (protocols) the
application that use them.

FTP over TCP


TCP is a dynamic reliable congestion control protocol. It uses Acknowledgements created
by the destination to know whether packets are well received.
There are number variants of the TCP protocol, such as Tahoe, Reno, NewReno,
Vegas. The type of agent appears in the first line:

set tcp [new Agent/TCP]

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.

#Setup a UDP connection


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

51
#setup a CBR over UDP connection
set cbr [new Application/Traffic/CBR]

$cbr attach-agent $udp

$cbr set packetsize_ 100

$cbr set rate_ 0.01Mb

$cbr set random_ false

Above shows the definition of a CBR application using a UDP agent


The command $ns attach-agent $n4 $sink defines the destination node. The command
$ns connect $tcp $sink finally makes the TCP connection between the source and destination
nodes.TCP has many parameters with initial fixed defaults values that can be changed if
mentioned explicitly. For example, the default TCP packet size has a size of 1000bytes.This can
be changed to another value, say 552bytes, using the command $tcp set packetSize 552.

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.

CBR over UDP


A UDP source and destination is defined in a similar way as in the case of TCP.
Instead of defining the rate in the command $cbr set rate_ 0.01Mb, one can define the time
interval between transmission of packets using the command.

$cbr set interval_ 0.005

The packet size can be set to some value using

$cbr set packetSize_ <packet size>

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”

$ns at 1.0 “ $ftp start”

$ns at 124.0 “$ftp stop”

$ns at 124.5 “$cbr stop”

Structure of Trace Files


When tracing into an output ASCII file, the trace is organized in 12 fields as follows in fig
shown below, The meaning of the fields are:
Event Time From To PKT PKT Flags Fid Src Dest Seq Pkt
Node Node Type Size Addr Addr Num id

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

RESULT: Thus the congestion control algorithm is simulated by using NS2.

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:

Aim: To Study the Performance of TCP and UDP protocols.


.

Overview of TCP’s congestion control

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.

Slow start and congestion avoidance


In slow start, when a connection is established, the value of cwnd is first set to 1 and after each received
ACK the value is updated to cwnd = cwnd + 1 implying doubling of cwnd for each RTT. The exponential
growth of cwnd continues until a packet loss is observed, causing the value of ssthresh to be updated to
ssthresh = cwnd/2. After the packet loss, the connection starts from slow start again with cwnd = 1, and
the window is increased exponentially until it equals ssthresh, the estimate for the available bandwidth

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.

Generation of nodes would be the first step to topology generation.


eg. # 0, 1, 2, 3, and 4 are sender nodes.
set n1 [$ns node]
# 5th node named as G is acting as gateway or intermediate node
set n5 [$ns node]
# 7th node is named R is acting as receiver connected through gateway node
set n7 [$ns node]

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.

For this purpose, we would like to suggest following syntax.


# Define different color for data flow.
$ns color 1 Red;
$ns color 2 Sea Green; $ns color 3 Blue;
59
This gives different colour to traffic generated between source n1 to receiver R, from n2 to R, n3 to R
and n4 to R. This research specifies the colours between different senders sending traffic to single
receiver and then next step is defining the edges between created nodes.

# create links between nodes


$ns duplex-link $n1 $n5 6mb 1ms Droptail
$ns duplex-link $G $n7 6mb 1ms Droptail

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.

Eg. $ns queue-limit $n5 $n7 5


The example in this research indicates that buffer size to accommodate unsent packets is set to 5 packets.
After 5 packets are added to queue, further congestion results to packet dropping.
$ns duplex-link-op $n1 $n5 orient right-up
$ns duplex-link-op $n2 $n5 orient right
$ns duplex-link-op $n3 $n5 orient right-down
$ns duplex-link-op $n4 $n5 orient right

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.

#Setup a TCP connection


set tcp [new Agent/TCP]
$ns attach-agent $n0 $tcp
set sink [new Agent/TCPSink]
$ns attach-agent $n7 $sin
$ns connect $tcp $sink $tcp set window_ 8 $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 $n4 $udp
set null [new Agent/Null]
$ns attach-agent $n7 $null
$ns connect $udp $null
$udp set fid_
60
#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

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.

we define finish procedure.


Proc finish {} {
global ns
$ns flush-trace
puts “running nam...”
exec nam -a out.nam &
exit 0 }
Above stated code sets global instance of ns and clear trace logs stored in trace file. Gives output string
indicating that now graphical version of simulator in the form of nam (network animator). Thereafter, it
executes NAM file. Finally it exits. Now the only thing remaining in our model is to set the start and
stop time for running our simulator model. This can be done as follows.
$ns at 0.5 “$ ftp, cbr start” $ns at 150.0 “$ ftp, cbr stop” $ns at 150.05 “finish”
$ns run
Thus, after calling the finish procedure, we have called the instance to run the created simulator model.
Before we can proceed with performance evaluation, we must choose the different metrics that would
help us in making comparisons. There could be different metrics to determine the performance like
throughput, delay, jitter, packet loss. The choice of metric would depend upon the purpose of the network
setup. The metrics could be related to the different layers of the
network stack. For example, TCP throughput is based on the application layer, whereas IP round trip
time is based on the network layer. For example, a network supporting multimedia applications should
have minimum delay and jitter. Packet loss might not be a critical issue for such a network. However,
packet loss might be a considerable factor for networks supporting textual data oriented applications,
something like someone downloading by FTP

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:

1. Differentiate between routing table and forwarding table.


2. How does a router differ from a bridge?
3. Define flooding. What is the drawback of flooding?
4. Write the features of Distance vector routing
5. What are the main disadvantages of distance vector routing?
6. What is routing protocol and how it is classified
7. Give comparison of unicast, multicast and broadcast routing.
8. What are the metrics used by routing protocols?
9. What are the benefits of Open Shortest Path First protocol

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:

1. What do you mean by error control?


2. How is error controlled in data link controlled protocol?
3. Write the concept of redundancy in error detection.
4. What are the three types of redundancy checks used in data communications
5. Write the concepts of CRC with example.
6. How can the parity bit detect a damaged data unit?
7. How can we use the Hamming code to correct a burst error?

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.

PROGRAM: (Stop and Wait Protocol)


# stop and wait protocol in normal situation
# features : labeling, annotation, nam-graph, and window size monitoring
set ns [new Simulator]
set n0 [$ns node]
set n1 [$ns node]
$ns at 0.0 "$n0 label Sender"
$ns at 0.0 "$n1 label Receiver"
set nf [open stop.nam w]
$ns namtrace-all $nf
set f [open stop.tr w]
$ns trace-all $f
$ns duplex-link $n0 $n1 0.2Mb 200ms DropTail
$ns duplex-link-op $n0 $n1 orient right
$ns queue-limit $n0 $n1 10
Agent/TCP set nam_tracevar_ true
set tcp [new Agent/TCP]
$tcp set window_ 1
$tcp set maxcwnd_ 1
$ns attach-agent $n0 $tcp
set sink [new Agent/TCPSink]
$ns attach-agent $n1 $sink
$ns connect $tcp $sink
set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ns add-agent-trace $tcp tcp
$ns monitor-agent-trace $tcp
$tcp tracevar cwnd_
$ns at 0.1 "$ftp start"
$ns at 3.0 "$ns detach-agent $n0 $tcp ; $ns detach-agent $n1 $sink"
$ns at 3.5 "finish"
$ns at 0.0 "$ns trace-annotate \"Stop and Wait with normal operation\""
$ns at 0.05 "$ns trace-annotate \"FTP starts at 0.1\""
$ns at 0.11 "$ns trace-annotate \"Send Packet_0\""
$ns at 0.35 "$ns trace-annotate \"Receive Ack_0\""
$ns at 0.56 "$ns trace-annotate \"Send Packet_1\""
$ns at 0.79 "$ns trace-annotate \"Receive Ack_1\""
$ns at 0.99 "$ns trace-annotate \"Send Packet_2\""
$ns at 1.23 "$ns trace-annotate \"Receive Ack_2 \""
$ns at 1.43 "$ns trace-annotate \"Send Packet_3\""
$ns at 1.67 "$ns trace-annotate \"Receive Ack_3\""
73
$ns at 1.88 "$ns trace-annotate \"Send Packet_4\""
$ns at 2.11 "$ns trace-annotate \"Receive Ack_4\""
$ns at 2.32 "$ns trace-annotate \"Send Packet_5\
$ns at 2.55 "$ns trace-annotate \"Receive Ack_5 \""
$ns at 2.75 "$ns trace-annotate \"Send Packet_6\""
$ns at 2.99 "$ns trace-annotate \"Receive Ack_6\""
$ns at 3.1 "$ns trace-annotate \"FTP stops\""
proc finish {} {
global ns nf
$ns flush-trace
close $nf
puts "running nam..."
exec nam stop.nam &
exit 0
}
$ns run
Output:

SLIDING WINDOW PROTOCOL:

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.

PROGRAM: (Sliding Window Protocol)


# sliding window mechanism with some features
# such as labeling, annotation, nam-graph, and window size monitoring
set ns [new Simulator]
set n0 [$ns node]
set n1 [$ns node]
$ns at 0.0 "$n0 label Sender"
$ns at 0.0 "$n1 label Receiver"
set nf [open sliding.nam w]
$ns namtrace-all $nf
set f [open sliding.tr w]
$ns trace-all $f
$ns duplex-link $n0 $n1 0.2Mb 200ms DropTail
$ns duplex-link-op $n0 $n1 orient right
$ns queue-limit $n0 $n1 10
Agent/TCP set nam_tracevar_ true
set tcp [new Agent/TCP]
$tcp set windowInit_ 4
$tcp set maxcwnd_ 4
$ns attach-agent $n0 $tcp
set sink [new Agent/TCPSink]
$ns attach-agent $n1 $sink
$ns connect $tcp $sink
set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ns add-agent-trace $tcp tcp
$ns monitor-agent-trace $tcp
$tcp tracevar cwnd_
$ns at 0.1 "$ftp start"
75
$ns at 3.0 "$ns detach-agent $n0 $tcp ; $ns detach-agent $n1 $sink"
$ns at 3.5 "finish"
$ns at 0.0 "$ns trace-annotate \"Sliding Window with window size 4 (normal operation)\""
$ns at 0.05 "$ns trace-annotate \"FTP starts at 0.1\""
$ns at 0.11 "$ns trace-annotate \"Send Packet_0,1,2,3\""
$ns at 0.34 "$ns trace-annotate \"Receive Ack_0,1,2,3\""
$ns at 0.56 "$ns trace-annotate \"Send Packet_4,5,6,7\""
$ns at 0.79 "$ns trace-annotate \"Receive Ack_4,5,6,7\""
$ns at 0.99 "$ns trace-annotate \"Send Packet_8,9,10,11\""
$ns at 1.23 "$ns trace-annotate \"Receive Ack_8,9,10,11 \""
$ns at 1.43 "$ns trace-annotate \"Send Packet_12,13,14,15\""
$ns at 1.67 "$ns trace-annotate \"Receive Ack_12,13,14,15\""
$ns at 1.88 "$ns trace-annotate \"Send Packet_16,17,18,19\""
$ns at 2.11 "$ns trace-annotate \"Receive Ack_16,17,18,19\""
$ns at 2.32 "$ns trace-annotate \"Send Packet_20,21,22,23\""
$ns at 2.56 "$ns trace-annotate \"Receive Ack_24,25,26,27\""
$ns at 2.76 "$ns trace-annotate \"Send Packet_28,29,30,31\""
$ns at 3.00 "$ns trace-annotate \"Receive Ack_28\""
$ns at 3.1 "$ns trace-annotate \"FTP stops\""
proc finish {} {
global ns
$ns flush-trace
# close $nf
puts "running nam..."
exec nam sliding.nam &
exit 0
}
$ns run

Output:

76
SIMULATION OF STOP-AND-WAIT PROTOCOL USING LAN TRAINER KIT

Connect the computers to the Scientech 5002Ausing RJ45 cables

● Switch on the power supply of Scientech 5002A.


● Open Scientech 5002A software
● Click on ‘Star Topology’

A window will appear on screen as shown

 Type IP address and Computer name of each connected node.


 Now select Stop N wait from top down menu

 Select all other settings like; frame size, inter frame delay, & bit error rate

 Now enter the destination node Name/IP Address.

77
 Now choose the parameters

 Click on ‘Save Parameters’


 ‘Ready for communication…..’ message will be displayed in status window of both
 source node & destination node
 Click on ‘Open’ to open a .txt file to transmit
 Now click on open
 Now click on send data

 we can see a frame status with blue color and Acknowledge status with red color

 We can see number of frames formed

 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

In addition to University Syllabus, additional lab exercises are implemented to clearly


understand the concepts and gain more confidence from learning.

The additional exercises are as,

o Study of Header files


o Study of Socket Programming and Client – Server model
o Simulation of Stop-and-wait & Sliding Window Protocol
o Simulation Of Stop-And-Wait Protocol
using NS2
using Lan Trainer Kit

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

You might also like