Sie sind auf Seite 1von 94

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

CS8581 – NETWORKS LABORATORY

(Regulation 2017)

Lab Learning Material

Academic Year 2019-2020 (Odd Sem)

Prepared By

Dr.K.Vishnukumar ASP/CSE

Dr.N.Prasath ASP / CSE


Mr.M.Saravanan, AP (Sr.G) /CSE
1

TABLE OF CONTENTS

Ex.No Content Page No.

- Authenticated Syllabus Copy 1


- List of Exercise 2
- Student’s slot & Batch details 3
- Lab plan 4
Learn to use commands like tcpdump, netstat, ifconfig,
1 nslookup and traceroute. Capture ping and traceroute PDUs 5
using a network protocol analyzer and examine.
Write a HTTP web client program to download a web page
2 using TCP sockets. 13
Applications using TCP sockets like:
 Echo client and echo server
3  Chat 20

 File Transfer

4 Simulation of DNS using UDP sockets. 28


5 Write a code simulating ARP /RARP protocols. 35
Study of Network simulator (NS) and Simulation of
6 44
Congestion Control Algorithms using Ns
7 Study of TCP/UDP performance using Simulation tool. 50
Simulation of Distance Vector/ Link State Routing
8 56
algorithm.
Performance evaluation of routing protocols using
9 62
simulation tool

10 Simulation of error correction code(like CRC) 68

11 MULTICASTING ROUTING PROTOCOL (Content Beyond 73


the syllabus)

Lab Learning Material III Year/V CS8581-Networks Lab


Sem Laboratory
2

Syllabus

Lab Learning Material III Year/V CS8581-Networks Lab


Sem Laboratory
3

List of Exercise

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:
• Echo client and echo server
• Chat
• File Transfer

4. Simulation of DNS using UDP sockets.


5. Write a code simulating ARP /RARP protocols.
6. Study of Network simulator (NS) and Simulation of Congestion Control Algorithms using NS.
7. Study of TCP/UDP performance using Simulation tool.
8. Simulation of Distance Vector/ Link State Routing algorithm.
9. Performance evaluation of routing protocols using simulation tool.
10. Simulation of error correction code (like CRC).
11. Content Beyond the syllabus.

Lab Learning Material III Year/V CS8581-Networks Lab


Sem Laboratory
4

Student’s slot & Batch details

Lab Learning Material III Year/V CS8581-Networks Lab


Sem Laboratory
5

Lab Learning Material III Year/V CS8581-Networks Lab


Sem Laboratory
6

Lab Learning Material III Year/V CS8581-Networks Lab


Sem Laboratory
7

LAB PLAN

CLASS : III Year/V Sem- A, B and C


SUBJECT : CS8581-Networks Laboratory
STAFFIN-CHARGE : Dr.K.Vishnukumar, Mr.M.Saravanan & Dr.N.Prasath

Ex Periods to complete the experiments


p
.No 3 6 9 12 15 18 21 24 27 30 33 36 39 42 45 48 51 57 60

10

11

Total Hours Planned: 60 Hours

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


8

EX NO:1 Host networking commands

Procedure:
Execute commands in command prompt and look for the output.

Pre Lab Learning Material

i. tcpdump:

tcpdump command is a famous network packet analysing tool that is used to display TCP\IP & other
network packets being transmitted over the network attached to the system on which tcpdump has been installed.
Tcpdump uses libpcap library to capture the network packets & is available on almost all Linux/Unix flavors.
tcpdump command can read the contents from a network interface or from a previously created packet file
or we can also write the packets to a file to be used for later. One must use the tcpdump command as root or as a
user with sudo privileges.

By default, tcpdump is available on almost all Linux distributions but if that’s not the case for you, install it on
your system using the following method.

 CentOS/RHEL

Install tcpdump on CentOS & RHEL using the following command ,

$ sudo yum install tcpdump

 Fedora

On Fedora, install tcpdump using the following command,

$ dnf install tcpdump

 Ubuntu/Debian/Linux Mint

On Ubuntu or Debian or Linux Mint, install tcp dumo using the following command,

$ apt-get install tcpdump

For windows

Step 1 – Download and install Windump

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


9

You will need to place your network card into promiscuous mode – for this, install WinPcap.

Step 2 – Download and install WinPcap

Step 3 – Open a Command Prompt with Administrator Rights

Start > Accessories > Command Prompt

Right Click > Run As Administrator

Change the directory to your download directory – normally in windows this is:

cd c:\Users\Smile\Downloads

Smile will be replaced with your username eg cd c:\Users\your username\Downloads

Step 4 – Run windump to locate your network adapter.

Windump will list your adapter with a number.

You may have several adapters listed. You select the interface to start running windump (as shown in step 5
using interface number 2).

Step 5 – Run windump to collect packets and write out to a file

windump -i 2 -q -w C:\perflogs\diagTraces -n -C 30 -W 10 -U -s 0

This will create a directory c:\perflogs\ and a file called diagTrace0.

The switches mean this:

 -i is the number of NIC selected in the previous step


 -q is quiet mode
 -w <name> is the prefix of the files to create
 -n the logging will not resolve host names, all data will be in IP address format
 -C the size in Millions of Bytes the logs files so grow to before moving to the next file
 -W the number of circular log files to retain in addition to the current log file, specify in <path> where the
files are to be stored
 -U as each packet is saved, it will be written to the output file
 -s decreases the amount of packet buffering, set this to zero.

Step 6 – Use Wireshark to Open your file

If you don’t have wireshark installed, download it from here.

File > Open > C:\perflogs > diagTraces0

Wireshark will reveal all the packet data. Double click on each event, to drill down to more data.

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


10

Or click on the “Protocol” Column, to sort by Arp, TCP, UDP or DNS etc.

ii. Netstat

Displays protocol statistics and current TCP/IP network connections.


NETSTAT [-a] [-e] [-n] [-s] [-p proto] [-r] [interval]
Displays all connections and listening ports. (Server-side connections are
-a
normally not shown).
-e Displays Ethernet statistics. This may be combined with the -s option.
-n Displays addresses and port numbers in numerical form.
Shows connections for the protocol specified by proto; proto may be tcp or
-p proto udp. If used with the -s option to display per-protocol statistics, proto may
be tcp, udp, or ip.
-r Displays the contents of the routing table.
Displays per-protocol statistics. By default, statistics are shown for TCP,
-s
UDP and IP; the -p option may be used to specify a subset of the default.
Redisplays selected statistics, pausing interval seconds between each
interval display. Press CTRL+C to stop redisplaying statistics. If omitted, netstat
will print the current configuration information once

Parameters
Parameter Description
nslookup exit
exits nslookup.
Command
nslookup finger
Connects with the finger server on the current computer.
Command
nslookup help Displays a short summary of nslookup subcommands.
nslookup ls lists information for a DNS domain.
nslookup lserver changes the default server to the specified DNS domain.
nslookup root changes the default server to the server for the root of the DNS domain name space.
nslookup server changes the default server to the specified DNS domain.
nslookup set changes configuration settings that affect how lookups function.
nslookup set all prints the current values of the configuration settings.
nslookup set
changes the query class. The class specifies the protocol group of the information.
class
nslookup set d2 Turns exhaustive Debugging mode on or off. All fields of every packet are printed.
nslookup set
Turns Debugging mode on or off.
debug
nslookup /set appends the default DNS domain name to a single component lookup request. A single
defname component is a component that contains no periods.
nslookup set changes the default DNS domain name to the name specified.
Lab Learning Material II Year/V Sem CS8581-Networks Laboratory
11

Parameter Description
domain
nslookup /set
Ignores packet truncation errors.
ignore
nslookup set port changes the default TCP/UDP DNS name server port to the value specified.
nslookup set
changes the resource record type for the query.
querytype
nslookup set
Tells the DNS name server to query other servers if it does not have the information.
recurse
nslookup set
Sets the number of retries.
retry
nslookup set root changes the name of the root server used for queries.
appends the DNS domain names in the DNS domain search list to the request until an answer is
nslookup set
received. This applies when the set and the lookup request contain at least one period, but do
search
not end with a trailing period.
nslookup set
changes the default DNS domain name and search list.
srchlist
nslookup set
changes the initial number of seconds to wait for a reply to a request.
timeout
nslookup set
changes the resource record type for the query.
type
nslookup set vc Specifies to use or not use a virtual circuit when sending requests to the server.
nslookup view sorts and lists the output of the previous ls subcommand or commands.

iii. Ifconfig (linux)


Interface configuration is a system administration utility in Unix-like operating systems to configure, control, and
query TCP/IP network interface parameters from a command line interface (CLI) or in system configuration scripts.

Ipconfig (windows)
(internet protocol configuration) in Microsoft Windows is a console application that displays all current TCP/IP
network configuration values and can modify Dynamic Host Configuration Protocol DHCP and Domain Name
System DNS settings.

 ipconfig - Briefly show you the configured network adapter’s information, such as IP address, subnet mask and
gateway.

 ipconfig /all - Show detailed information of network adapter that includes IP address, subnet mask, gateway, DNS,
DHCP, MAC address, etc.

 ipconfig /release - Release the IP address of network adapter, mainly used for network adapter that relies on DHCP
server to obtain IP address.

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


12

 ipconfig /renew - Renew the IP address of network adapter, mainly used for network adapter that relies on DHCP
server to obtain IP address.

 ipconfig /displaydns - Display the contents of the DNS Resolver Cache.

 ipconfig /flushdns - Clear the DNS Resolver cache.

 ipconfig /? - Display detailed command usage info.

iv. Nslookup
Displays information that you can use to diagnose Domain Name System (DNS) infrastructure. Before
using this tool, you should be familiar with how DNS works. The nslookup command-line tool is
available only if you have installed the TCP/IP protocol.

To illustrate the use of nslookup we are going to use it to:

 Find the IP address of a host.


 Find the domain name of an IP address.
 Find mail servers for a domain.

Finding The IP Address of an Host-

To find the ip address of a host e.g. www.steves-internet-guide.com type:

nslookup www.google.com

at a command prompt.

Reverse Lookup IP address to domain name

Type nslookup IP address

v. traceroute

A traceroute is a function which traces the path from one network to another. It allows us to diagnose the
source of many problems.

Note: To be effective, the traceroute MUST be run during a time when you are experiencing the problem, from a
computer that is experiencing the problem. A trace when you are able to connect, or one from another computer,
is not helpful. Therefore, you should try to connect to your site again just before you run it. If the problem is no
longer occurring, you will have to wait until the next time the problem occurs (if there is a next time) before
running your traceroute.

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


13

Tracert Command Options


Item Description
This option prevents tracert from resolving IP addresses to hostnames, often resulting in much faster
-d
results.
-h This tracert option specifies the maximum number of hops in the search for the target. If you do not
MaxHops specify MaxHops, and a target has not been found by 30 hops, tracert will stop looking.
-w You can specify the time, in milliseconds, to allow each reply before timeout using this tracert
TimeOut option.
-4 This option forces tracert to use IPv4 only.
-6 This option forces tracert to use IPv6 only.
target This is the destination, either an IP address or hostname.
Use the help switch with the tracert command to show detailed help about the command's several
/?
options.

Other less commonly used options for the tracert command also exist, including [-j HostList], [-R], and [-S
SourceAddress]. Use the help switch with the tracert command for more information on these options.

Capture ARP & ICMP Protocol Traffic using Wireshark.

Start a Wireshark capture. Open a Windows console window, and generate some ICMP traffic by using the Ping
command line tool to check the connectivity of a neighbouring machine (or your home router). Stop the capture
and Wireshark.

Pre Lab Questions:

1. Define networking?
2. What is a protocol? What are its key elements?
3. What is a buffer?
4. What is the use of TCP protocol?
5. What is the size of bits address used by IPV4?
6. What is the size of bits address used by IPV6?

Student Exercise:

1. tcpdump

Run windump to collect packets and write out to a file tcpdumofile.txt

2. netstat
View all established connection from/to your Windows server

3. ipconfig
Lab Learning Material II Year/V Sem CS8581-Networks Laboratory
14

Execute command that terminates any active TCP/IP connections on all network adapters.

Execute command that re-establishes TCP/IP connections on all network adapters.

4. Nslookup
Execute command to connect with the finger server on the current computer

5. Trace route
Use traceroute command for www.kpriet.ac.in and limit displaying number of hops to 3 and write the output to a
file named traceresults.txt

6. Ping
1. Ping the Default Gateway
2. Ping the Host Name
3. Ping Localhost
7. Trace route using wireshark
1. Activity 1 - Capture Tracert Traffic
2. Activity 2 - Analyze Tracert Traffic

Viva Questions:

What will be the output of tcpdump?


What is the use of ping command?
What is a port?
How to display the contents of the routing table using netstat?
What is the purpose of ipconfig command?
Can 2 devices have the same IP address? If so how do I resolve an IP address conflict?
What is IP command?
What is nslookup command?

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


15

EX No 2 Write a HTTP web client program to download a web page using TCP sockets

Procedure:

The steps for creating a simple server program are:

1. Open the Server Socket:


ServerSocket server = new ServerSocket( PORT );
2. Wait for the Client Request:
Socket client = server.accept();
3. Create I/O streams for communicating to the client
DataInputStream is = new DataInputStream(client.getInputStream());
DataOutputStream os = new DataOutputStream(client.getOutputStream());
4. Perform communication with client
Receive from client: String line = is.readLine();
Send to client: os.writeBytes(“Hello\n”);
5. Close socket:
client.close();

The steps for creating a simple client program are:


1. Create a Socket Object:
Socket client = new Socket(server, port_id);
2. Create I/O streams for communicating with the server.
is = new DataInputStream(client.getInputStream());
os = new DataOutputStream(client.getOutputStream());
3. Perform I/O or communication with the server:
Receive data from the server:
String line = is.readLine();
Send data to the server: os.writeBytes(“Hello\n”);
4. Close the socket when done:
client.close();

Pre Lab Learning Material

Client/Server Communication
At a basic level, network-based systems consist of a server , client , and a media for communication as shown in
Fig. A computer running a program that makes a request for services is called client machine. A computer
running a program that offers requested services from one or more clients is called server machine. The media for
communication can be wired or wireless network.

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


16

Generally, programs running on client machines make requests to a program (often called as server program)
running on a server machine. They involve networking services provided by the transport layer, which is part of
the Internet software stack, often called TCP/IP (Transport Control Protocol/Internet Protocol) stack, shown in
Fig.

The transport layer comprises two types of protocols, TCP (Transport Control Protocol) and UDP (User
Datagram Protocol). The most widely used programming interfaces for these protocols are sockets.

TCP is a connection-oriented protocol that provides a reliable fl ow of data between two computers. Example
applications that use such services are HTTP, FTP, and Telnet.

UDP is a protocol that sends independent packets of data, called datagrams, from one computer to another with
no guarantees about arrival and sequencing. Example applications that use such services include Clock server and
Ping.

The TCP and UDP protocols use ports to map incoming data to a particular process running on a computer. Port
is represented by a positive (16-bit) integer value. Some ports have been reserved to support common/well known
services:

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


17

Fig. TCP/UDP mapping of incoming packets to appropriate port/process

Object-oriented Java technologies—Sockets, threads, RMI, clustering, Web services—have emerged as leading
solutions for creating portable, effi cient, and maintainable large and complex Internet applications.

Hosts Identification and Service Ports

Every computer on the Internet is identified by a unique, 4-byte IP address . This is typically written in dotted
quad format like 128.250.25.158 where each byte is an unsigned value between 0 and 255. This representation is
clearly not user-friendly because it does not tell us anything about the content and then it is difficult to remember.
Hence, IP addresses are mapped to names like www.buyya.com or www.google.com, which are easier to
remember. Internet supports name servers that translate these names to IP addresses.

In general, each computer only has one Internet address. However, computers often need to communicate and
provide more than one type of service or to talk to multiple hosts/computers at a time. For example, there may be
multiple ftp sessions, web connections, and chat programs all running at the same time. To distinguish these
services, a concept of port s, a logical access point, represented by a 16-bit integer number is used. That means,
each service offered by a computer is uniquely identified by a port number. Each Internet packet contains both
the destination host address and the port number on that host to which the message/request has to be delivered.
The host computer dispatches the packets it receives to programs by looking at the port numbers specified within
the packets. That is, IP address can be thought of as a house address when a letter is sent via post/snail mail and
port number as the name of a specifi c individual to whom the letter has to be delivered.

Sockets and Socket-based Communication

Sockets provide an interface for programming networks at the transport layer. Network communication using
Sockets is very much similar to performing fi le I/O. In fact, socket handle is treated like file handle.
The streams used in file I/O operation are also applicable to socket-based I/O. Socket-based communication is
independent of a programming language used for implementing it. That means, a socket program written in Java
language can communicate to a program written in non-Java (say C or C++) socket program.

A server (program) runs on a specific computer and has a socket that is bound to a specifi c port. The server
listens to the socket for a client to make a connection request (see Fig. 13.4a).

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


18

If everything goes well, the server accepts the connection (see Fig.). Upon acceptance, the server gets a new
socket bound to a different port. It needs a new socket (consequently a different port number) so that it can
continue to listen to the original socket for connection requests while serving the connected client.

SOCKET PROGRAMMING AND JAVA.NET CLASS

A socket is an endpoint of a two-way communication link between two programs running on the network.
Socket is bound to a port number so that the TCP layer can identify the application that data is destined to be
sent. Java provides a set of classes, defi ned in a package called java.net, to enable the rapid development of
network applications. Key classes, interfaces, and exceptions in java.net package simplifying the complexity
involved in creating client and server programs are:

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


19

TCP/IP SOCKET PROGRAMMING


The two key classes from the java.net package used in creation of server and client programs are:

 ServerSocket
 Socket

A server program creates a specific type of socket that is used to listen for client requests (server socket), In the
case of a connection request, the program creates a new socket through which it will exchange data with the
client using input and output streams. The socket abstraction is very similar to the fi le concept: developers have
to open a socket, perform I/O, and close it. Figure illustrates key steps involved in creating socket-based server
and client programs.

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


20

Pre Lab Questions:

1. What is a server?
2. What is HTTP?
3. Explain client server communication?
4. What is TCP/IP?
5. What are the protocols used by the transport layer?

Sample programs

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


21

Output
Compile both server and client programs and then deploy server program code on a machine which is
going to act as a server and client program, which is going to act as a client. If required, both client and server
programs can run on the same machine. To illustrate execution of server and client programs, let us assume that a
machine called mundroo.csse.unimelb.edu.au on which we want to run a server program as indicated below:

java SimpleServer

The client program can run on any computer in the network (LAN, WAN, or Internet) as long as there is
no fi rewall between them that blocks communication. Let us say we want to run our client program on a machine
called gridbus.csse.unimelb.edu.au as follows:

java SimpleClient

The client program is just establishing a connection with the server and then waits for a message. On
receiving a response message, it prints the same to the console.

The output in this case is: Hi there

Which is sent by the server program in response to a client connection request.


Lab Learning Material II Year/V Sem CS8581-Networks Laboratory
22

Student Exercise:

1. Write a HTTP web client program to download a web page “www.kpriet.ac.in” using TCP sockets

Viva Questions:

1. List the port numbers which are reserves for common services like FTP, telnet, smtp, http, https.
2. List any 4 classes in java.net package
3. List any four interfaces in java.net package
4. List any 2 exceptions in java.net package
5. How to create I/O streams for communicating to the client?
6. What is a TCP socket connection?
7. What is difference between socket () and ServerSocket () class?
8. What is TCP and UDP socket?
9. How does TCP socket work?
10. What is difference between socket and port?
11. What is the difference between TCP and IP protocols?
12. Is UDP better than TCP?
13. Is port 80 TCP or UDP?

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


23

EX No 3 Create applications using TCP sockets

(a. Echo client and echo server b. Chat c. File Transfer)

Procedure:

a. Echo client and echo server

Server

Step 1: Start.
Step 2: Create a serversocket object.
Step 3: Create a socket object.
Step 4: Connect the socket object to DataOutputStream.
Step 5: Repeat steps 6 until ‘exit’ is typed.
Step 6: Sent message to client
Step 7: Close serversocket object
Step 8: Stop

Client

Step 1: Start
Step 2: Create a socket object.
Step 3: Get inputstream from server
Step 4: Print input from server
Step 5: Stop

b. Chat
Step 1: In any Client/Server Application, we need to run the server before the

client, because the server keeps waiting for the client to be connected.

Step 2: Server keeps listening for the client on an assigned IP & Port

Step 3: For establishing connection client must know the IP & Port of the server.

Step 4: When we start Client Application, It creates a connection to the server.

Step 5: After the Successful connection Client & Server Applications can send &

receive messages.

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


24

Pre Lab Learning Material:

a) Echo client and echo server

In Internet the traffic is control by strict protocol. There are two types of Internet Protocol (IP).
Types of Internet Protocol (IP)
1. TCP (Transmission Control Protocol) and
2.UDP (User or Universal Datagram Protocol)

TCP is connection oriented – reliable protocol which transfers the data in continues streams. Once a connection
is established, data can be sent bidirectional. It is a two way communication.
UDP is a connection less, independent, self contained protocol. Bulk Data are send and receive as packets from
using UDP.
Whether you are sending a packet via TCP or UDP, the packet is sent to an IP address. These packets are
forwarded from your computer to the destination via on Internet router.

Process of Communication
First when client send request to server means that when you load a web page, your computer sends TCP
(bytes forms) packets to the web server’s address, then server send the web page to you as response.
The web server sending a stream of TCP packets as response, which your web browser receive the web pages and
display it to you.

The java.net package is required for socket programming, and the java.io package is required to support I/O
operations, and

Java.net package provide two class


Server Socket class and socket class

Server Socket class creates stream socket and connect with specific port ,ip address,host name.
where socket class which is known listen Socket which class creates another socket for listen to the client

readLine() method in BufferedReader object is created to read the input from keyboard (write on console)

GetInputStream() method in InputStreamReader is for receive(read) the input stream where System.in as a
parameter to InputStreamReader.
getOutputStream() method in DataOutputStream which sent(write) output stream data to other side
of computer.

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


25

b) Chat Program Java is a continuous communication between two systems. Networking chapter also (apart
threads, DS etc.) proves that Java language is simple to develop applications that are difficult (requires extra
practice and experience) in other languages.

Before going into the details of client-server communication, it is advised to go through Networking –
Introduction and Communication with TCP/IP Protocol to know the terms and basics of networking and the way
Java supports.

Total 4 programs are given in TCP/IP protocol based communication.

Application Number Functionality


1st application Client to server communication (one-way)
2nd application Server to client communication (one-way)
3rd application Server sends file contents to client (two-way, non-continuous)
4th application Chat program (two-way, continuous)

4th application – Chat Program Java: Chat communication (two-way continuous)

This is the last one of the four series where client and server talks continuously until one disconnets.

Chat communication is the process of exchanging messages between two systems continuously. Anyone can
break the communication. Both systems come with the following same responsibilities.

1. Reading from keyboard. Uses an input stream like BufferedReader connected to System.in.
2. Sending data to the other system what is read from keyboard. Uses an output stream like PrintWriter
connected to getOutputStream() method of Socket.
3. Receiving data from the other system. Uses an input stream like BufferedReader connected to
getInputStream() method of Socket.

As the responsibilities are same, both client and server programs contain the same stream objects and same code.

c) How to transfer files between 2 computers.

You may transfer any file between any 2 systems in which one system acts as a Server and the other one act as a
client. You can implement the logic in making a chat application with file transfer.

Server.java

First we will discuss the coding for server side, we are going to import all the classes which are needed by the
Server class:

Listing1 : Importing classes

array0

Here java.net is for importing the ServerSocket and the Socket class. These classes are used for defining the
server connection port number and also are used for accepting connections from the client.
Lab Learning Material II Year/V Sem CS8581-Networks Laboratory
26

Now we define the class along with the main function:

Listing2: Class and main method

public class Server {

public static void main (String [] args ) throws IOException {

ServerSocket serverSocket = new ServerSocket(15123);

The name of class is Server, we defined a variable serverSocket of ServerSocket type inside the main method.
Actually here serverSocket waits for incoming client connection on port 15123 which is specified as argument
above (chosen randomly) and accepts the connection when it gets one.

Now we will define the main logic in the program:

Listing3 : Main Logic

Socket socket = serverSocket.accept();


System.out.println("Accepted connection : " + socket);
File transferFile = new File ("Document.doc");
byte [] bytearray = new byte [(int)transferFile.length()];
FileInputStream fin = new FileInputStream(transferFile);
BufferedInputStream bin = new BufferedInputStream(fin);
bin.read(bytearray,0,bytearray.length);
OutputStream os = socket.getOutputStream();
System.out.println("Sending Files...");
os.write(bytearray,0,bytearray.length);
os.flush();
socket.close();
System.out.println("File transfer complete");

}
}

Now we explain this:

serverSocket.accept() waits for any client connection and once any clients tries on to connect on server it accepts
the connection and then store it in socket object of the Socket class.

We define the file to be transferred as Document.doc in a file variable named transferFile. We define a bytearray
which will contain temporary data, define the fin and bin object to read from the transferFile and the data read
would be filled in the bytearray object, bin.read method is used to read the file and the data read is stored in the
bytearray.

We define a OutStream which here provides a channel to communicate with client side. We write the data read
from the bytearray onto the output stream.

We close the objects using the close method.

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


27

Client.java

Now we will come to coding at Client side:

First we import all the classes.

Listing4: Import classes

array0

Here java.net is for importing the Socket class. These classes are used for defining the server ip address and the
port number of the server.

Now we will define the class and the main method:

Listing5: Defining classes and methods

public class Client {

public static void main (String [] args ) throws IOException {


int filesize=2022386;
int bytesRead;
int currentTot = 0;

We defined a class named Client, Main method and a variable filesize which can be thought of like a buffer size.

bytesRead contain the current statistics of the bytes read from the input channel ie inputstream, currentTot
contains the total number of bytes read.

Now we will add the processing part:

Listing6: Main Logic

Socket socket = new Socket("127.0.0.1",15123);


byte [] bytearray = new byte [filesize];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream("copy.doc");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(bytearray,0,bytearray.length);
currentTot = bytesRead;

do {
bytesRead =
is.read(bytearray, currentTot, (bytearray.length-currentTot));
if(bytesRead >= 0) currentTot += bytesRead;
} while(bytesRead > -1);

bos.write(bytearray, 0 , currentTot);
bos.flush();
bos.close();
socket.close();
}
}

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


28

We defined a Socket object which try to connect on ip 127.0.0.1(local ip in my case, change it when you try on
lan with ip of your friends computer) on port number 15123. We define a variable byteArray which will act just
like a buffer to hold temporary data, InputStream object called in which will help us to collect all information
passed to input channel of client ie files or even the messages which are transferred to client.

We define the FileOutputStream object which point to the file which will be filled with data copied from the
server file. The BufferedOutputStream helps us to write data to the output file via a byte array.

We read the data from the inputstream using the read method of the object. The data read from the input channel
is stored in the byte array. We initially set currentTot to number of bytes read.

Now we implement a do-while loop. It read again from the input stream and now if the bytesRead is >=0 then we
update out currentTot object. When the byteRead is -1 i.e. there is no data left on the inputstream then the do-
while loop exits.

After that we write the finally read bytes on the file and then close the stream.

Pre Lab Questions:

1. What is the syntax for main class in java?


2. How to create a socket?
3. How to read input from the user on the standard input stream?
4. What is the use of BufferedReader?
5. How to create object in java?
6. What is command line argument?

Sample programs:

Echo client and echo server

EchoServer.java

import java.io.*;
import java.net.*;

public class EchoServer


{
public EchoServer(int portnum)
{
try
{
server = new ServerSocket(portnum);
}
Lab Learning Material II Year/V Sem CS8581-Networks Laboratory
29

catch (Exception err)


{
System.out.println(err);
}
}

public void serve()


{
try
{
while (true)
{
Socket client = server.accept();
BufferedReader r = new BufferedReader(new
InputStreamReader(client.getInputStream()));
PrintWriter w = new PrintWriter(client.getOutputStream(), true);
w.println("Welcome to the Java EchoServer. Type 'bye' to close.");
String line;
do
{
line = r.readLine();
if ( line != null )
w.println("Got: "+ line);
}
while ( !line.trim().equals("bye") );
client.close();
}
}
catch (Exception err)
{
System.err.println(err);
}
}

public static void main(String[] args)


{
EchoServer s = new EchoServer(9999);
s.serve();
}

private ServerSocket server;


}

Echo.Client.java

import java.io.*;
import java.net.*;

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


30

public class EchoClient


{
public static void main(String[] args)
{
try
{
Socket s = new Socket("127.0.0.1", 9999);
BufferedReader r = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter w = new PrintWriter(s.getOutputStream(), true);
BufferedReader con = new BufferedReader(new InputStreamReader(System.in));
String line;
do
{
line = r.readLine();
if ( line != null )
System.out.println(line);
line = con.readLine();
w.println(line);
}
while ( !line.trim().equals("bye") );
}
catch (Exception err)
{
System.err.println(err);
}
}
}

c) Sample Source code for file transfer using TCP sockets

Listing7: Server code

import java.net.*;
import java.io.*;
public class Server {

public static void main (String [] args ) throws IOException {

ServerSocket serverSocket = new ServerSocket(15123);


Socket socket = serverSocket.accept();
System.out.println("Accepted connection : " + socket);
File transferFile = new File ("Document.doc");
byte [] bytearray = new byte [(int)transferFile.length()];
FileInputStream fin = new FileInputStream(transferFile);
BufferedInputStream bin = new BufferedInputStream(fin);
bin.read(bytearray,0,bytearray.length);
OutputStream os = socket.getOutputStream();
System.out.println("Sending Files...");
Lab Learning Material II Year/V Sem CS8581-Networks Laboratory
31

os.write(bytearray,0,bytearray.length);
os.flush();
socket.close();
System.out.println("File transfer complete");
}
}

Listing8: Client code

import java.net.*;
import java.io.*;
public class Client {

public static void main (String [] args ) throws IOException {


int filesize=1022386;
int bytesRead;
int currentTot = 0;
Socket socket = new Socket("127.0.0.1",15123);
byte [] bytearray = new byte [filesize];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream("copy.doc");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(bytearray,0,bytearray.length);
currentTot = bytesRead;

do {
bytesRead =
is.read(bytearray, currentTot, (bytearray.length-currentTot));
if(bytesRead >= 0) currentTot += bytesRead;
} while(bytesRead > -1);

bos.write(bytearray, 0 , currentTot);
bos.flush();
bos.close();
socket.close();
}
}

Output:

a. Echo client and echo server

EchoServer
:/>javac EchoServer.java
:/>java EchoServer

EchoClient
:/>javac EchoClient.java
:/>java EchoClient

Welcome to the Java EchoServer. Type 'bye' to close.


HAI
Got: HAI
Lab Learning Material II Year/V Sem CS8581-Networks Laboratory
32

Hello
Got: Hello
bye
Press any key to continue ….

Student Exercise:

1. Write a client server echo program to display “welcome to computer networks lab”
2. Write a client server echo program to run the chat application in Java
3. Write a file transfer application to transfer file “one.txt” from server to client.

Viva Questions:

1. How to create a new Socket object?


2. What is the use of a constructor?
3. What is the use of try{} block?
4. Name the various I/O in java?
5. What is InputStream and OutputStream?
6. What is the use of IOException?

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


33

EX No 4 Simulation of DNS using UDP sockets

Procedure:

Pre Lab Learning Material:

The Domain Name Systems (DNS) is the phonebook of the Internet. Humans access information online through
domain names, like nytimes.com or espn.com. Web browsers interact through Internet Protocol (IP) addresses.
DN S translates domain names to IP addresses so browsers can load Internet resources.

Each device connected to the Internet has a unique IP address which other machines use to find the device. DNS
servers eliminate the need for humans to memorize IP addresses such as 192.168.1.1 (in IPv4), or more complex
newer alphanumeric IP addresses such as 2400:cb00:2048:1::c629:d7a2 (in IPv6).

How does DNS work?

The process of DNS resolution involves converting a hostname (such as www.example.com) into a computer-
friendly IP address (such as 192.168.1.1). An IP address is given to each device on the Internet, and that address
is necessary to find the appropriate Internet device - like a street address is used to find a particular home. When
a user wants to load a webpage, a translation must occur between what a user types into their web browser
(example.com) and the machine-friendly address necessary to locate the example.com webpage.

In order to understand the process behind the DNS resolution, it’s important to learn about the different hardware
components a DNS query must pass between. For the web browser, the DNS lookup occurs “ behind the scenes”
and requires no interaction from the user’s computer apart from the initial request.

There are 4 DNS servers involved in loading a webpage:

 DNS recursor - The recursor can be thought of as a librarian who is asked to go find a particular book somewhere
in a library. The DNS recursor is a server designed to receive queries from client machines through applications
such as web browsers. Typically the recursor is then responsible for making additional requests in order to satisfy
the client’s DNS query.
 Root nameserver - The root server is the first step in translating (resolving) human readable host names into IP
addresses. It can be thought of like an index in a library that points to different racks of books - typically it serves as
a reference to other more specific locations.
 TLD nameserver - The top level domain server (TLD) can be thought of as a specific rack of books in a library.
This nameserver is the next step in the search for a specific IP address, and it hosts the last portion of a hostname
(In example.com, the TLD server is “com”).
 Authoritative nameserver - This final nameserver can be thought of as a dictionary on a rack of books, in which a
specific name can be translated into its definition. The authoritative nameserver is the last stop in the nameserver
query. If the authoritative name server has access to the requested record, it will return the IP address for the
 requested hostname back to the DNS Recursor (the librarian) that made the initial request.

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


34

What's the difference between an authoritative DNS server and a recursive DNS resolver?

Both concepts refer to servers (groups of servers) that are integral to the DNS infrastructure, but each performs a
different role and lives in different locations inside the pipeline of a DNS query. One way to think about the
difference is the recursive resolver is at the beginning of the DNS query and the authoritative nameserver is at the
end.

Recursive DNS resolver

The recursive resolver is the computer that responds to a recursive request from a client and takes the time to
track down the DNS record. It does this by making a series of requests until it reaches the authoritative DNS
nameserver for the requested record (or times out or returns an error if no record is found). Luckily, recursive
DNS resolvers do not always need to make multiple requests in order to track down the records needed to
respond to a client; caching is a data persistence process that helps short-circuit the necessary requests by serving
the requested resource record earlier in the DNS lookup.

Authoritative DNS server

Put simply, an authoritative DNS server is a server that actually holds, and is responsible for, DNS resource
records. This is the server at the bottom of the DNS lookup chain that will respond with the queried resource
record, ultimately allowing the web browser making the request to reach the IP address needed to access a
website or other web resources. An authoritative nameserver can satisfy queries from its own data without
needing to query another source, as it is the final source of truth for certain DNS records.

It’s worth mentioning that in instances where the query is for a subdomain such as foo.example.com or
blog.cloudflare.com, an additional nameserver will be added to the sequence after the authoritative nameserver,
which is responsible for storing the subdomain’s CNAME record.

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


35

There is a key difference between many DNS services and the one that Cloudflare provides. Different DNS
recursive resolvers such as Google DNS, OpenDNS, and providers like Comcast all maintain data center
installations of DNS recursive resolvers. These resolvers allow for quick and easy queries through optimized
clusters of DNS-optimized computer systems, but they are fundamentally different than the nameservers hosted
by Cloudflare.

Cloudflare maintains infrastructure-level nameservers that are integral to the functioning of the Internet. One key
example is the f-root server network which Cloudflare is partially responsible for hosting. The F-root is one of
the root level DNS nameserver infrastructure components responsible for the billions of Internet requests per day.
Our any cast network puts us in a unique position to handle large volumes of DNS traffic without service
interruption.

What are the steps in a DNS lookup?

For most situations, DNS is concerned with a domain name being translated into the appropriate IP address. To
learn how this process works, it helps to follow the path of a DNS lookup as it travels from a web browser,
through the DNS lookup process, and back again. Let's take a look at the steps.

Note: Often DNS lookup information will be cached either locally inside the querying computer or remotely in
the DNS infrastructure. There are typically 8 steps in a DNS lookup. When DNS information is cached, steps are
skipped from the DNS lookup process which makes it quicker. The example below outlines all 8 steps when
nothing is cached.

The 8 steps in a DNS lookup:

1. A user types ‘example.com’ into a web browser and the query travels into the Internet and is received by a DNS
recursive resolver.
2. The resolver then queries a DNS root nameserver (.).
3. The root server then responds to the resolver with the address of a Top Level Domain (TLD) DNS server (such as
.com or .net), which stores the information for its domains. When searching for example.com, our request is
pointed toward the .com TLD.
4. The resolver then makes a request to the .com TLD.
5. The TLD server then responds with the IP address of the domain’s nameserver, example.com.
Lab Learning Material II Year/V Sem CS8581-Networks Laboratory
36

6. Lastly, the recursive resolver sends a query to the domain’s nameserver.


7. The IP address for example.com is then returned to the resolver from the nameserver.
8. The DNS resolver then responds to the web browser with the IP address of the domain requested initially.

Once the 8 steps of the DNS lookup have returned the IP address for example.com, the browser is able to
make the request for the web page:

9. The browser makes a HTTP request to the IP address.


10. The server at that IP returns the webpage to be rendered in the browser (step 10).

What is a DNS resolver?

The DNS resolver is the first stop in the DNS lookup, and it is responsible for dealing with the client that made
the initial request. The resolver starts the sequence of queries that ultimately leads to a URL being translated into
the necessary IP address.

Note: A typical uncached DNS lookup will involve both recursive and iterative queries.

It's important to differentiate between a recursive DNS query and a recursive DNS resolver. The query refers to
the request made to a DNS resolver requiring the resolution of the query. A DNS recursive resolver is the
computer that accepts a recursive query and processes the response by making the necessary requests.

What are the types of DNS Queries?


In a typical DNS lookup three types of queries occur. By using a combination of these queries, an optimized
process for DNS resolution can result in a reduction of distance traveled. In an ideal situation cached record data
will be available, allowing a DNS name server to return a non-recursive query.
Lab Learning Material II Year/V Sem CS8581-Networks Laboratory
37

3 types of DNS queries:

1. Recursive query - In a recursive query, a DNS client requires that a DNS server (typically a DNS recursive
resolver) will respond to the client with either the requested resource record or an error message if the resolver can't
find the record.
2. Iterative query - in this situation the DNS client will allow a DNS server to return the best answer it can. If the
queried DNS server does not have a match for the query name, it will return a referral to a DNS server authoritative
for a lower level of the domain namespace. The DNS client will then make a query to the referral address. This
process continues with additional DNS servers down the query chain until either an error or timeout occurs.
3. Non-recursive query - typically this will occur when a DNS resolver client queries a DNS server for a record that
it has access to either because it's authoritative for the record or the record exists inside of its cache. Typically, a
DNS server will cache DNS records to prevent additional bandwidth consumption and load on upstream servers.

What is DNS caching? Where does DNS caching occur?


The purpose of caching is to temporarily stored data in a location that results in improvements in performance
and reliability for data requests. DNS caching involves storing data closer to the requesting client so that the DNS
query can be resolved earlier and additional queries further down the DNS lookup chain can be avoided, thereby
improving load times and reducing bandwidth/CPU consumption. DNS data can be cached in a variety of
locations, each of which will store DNS records for a set amount of time determined by a time-to-live (TTL).

Browser DNS caching

Modern web browsers are designed by default to cache DNS records for a set amount of time. the purpose here is
obvious; the closer the DNS caching occurs to the web browser, the fewer processing steps must be taken in
order to check the cache and make the correct requests to an IP address. When a request is made for a DNS
record, the browser cache is the first location checked for the requested record.

In chrome, you can see the status of your DNS cache by going to chrome://net-internals/#dns.

Operating system (OS) level DNS caching

The operating system level DNS resolver is the second and last local stop before a DNS query leaves your
machine. The process inside your operating system that is designed to handle this query is commonly called a
“stub resolver” or DNS client. When a stub resolver gets a request from an application, it first checks its own
cache to see if it has the record. If it does not, it then sends a DNS query (with a recursive flag set), outside the
local network to a DNS recursive resolver inside the Internet service provider (ISP).

When the recursive resolver inside the ISP receives a DNS query, like all previous steps, it will also check to see
if the requested host-to-IP-address translation is already stored inside its local persistence layer.

The recursive resolver also has additional functionality depending on the types of records it has in its cache:

1. If the resolver does not have the A records, but does have the NS records for the authoritative nameservers, it will
query those name servers directly, bypassing several steps in the DNS query. This shortcut prevents lookups from
the root and .com nameservers (in our search for example.com) and helps the resolution of the DNS query occur
more quickly.
2. If the resolver does not have the NS records, it will send a query to the TLD servers (.com in our case), skipping the
root server.

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


38

3. In the unlikely event that the resolver does not have records pointing to the TLD servers, it will then query the root
servers. This event typically occurs after a DNS cache has been purged.

How to program using UDP protocol?


You will learn how to code a client/server application based on UDP protocol.
First, let’s see how Java Network API is designed to support development of network applications that make use
of UDP.
DatagramPacket and DatagramSocket are the two main classes that are used to implement a UDP client/server
application. DatagramPacket is a data container and DatagramSocket is a mechanism to send and receive
DatagramPackets.

1. DatagramPacket
In UDP’s terms, data transferred is encapsulated in a unit called datagram. A datagram is an independent, self-
contained message sent over the network whose arrival, arrival time, and content are not guaranteed. And in Java,
DatagramPacket represents a datagram.
You can create a DatagramPacket object by using one of the following constructors:

 DatagramPacket(byte[] buf, int length)

 DatagramPacket(byte[] buf, int length, InetAddress address, int port)

As you can see, the data must be in the form of an array of bytes. The first constructor is used to create a
DatagramPacket to be received.
The second constructor creates a DatagramPacket to be sent, so you need to specify the address and port number
of the destination host.
The parameter length specifies the amount of data in the byte array to be used, usually is the length of the array
(buf.length).

There are also other constructors that allow you to specify the offset in the byte array, as well as using a
SocketAddress:

 DatagramPacket(byte[] buf, int offset, int length)

 DatagramPacket(byte[] buf, int offset, int length, SocketAddress address)

In addition, the DatagramPacket provides setter and getter methods for address, data and port number. Consult its
DatagramPacket Javadoc for full details.

2. DatagramSocket
You use DatagramSocket to send and receive DatagramPackets. DatagramSocket represents a UDP connection
between two computers in a network.
In Java, we use DatagramSocket for both client and server. There are no separate classes for client and server like
TCP sockets.
So you create a DatagramSocket object to establish a UDP connection for sending and receiving datagram, by
using one of the following constructors:

 DatagramSocket()
Lab Learning Material II Year/V Sem CS8581-Networks Laboratory
39

 DatagramSocket(int port)

 DatagramSocket(int port, InetAddress laddr)

The no-arg constructor is used to create a client that binds to an arbitrary port number. The second constructor is
used to create a server that binds to the specific port number, so the clients know how to connect to.
And the third constructor binds the server to the specified IP address (in case the computer has multiple IP
addresses).
These constructors can throw SocketException if the socket could not be opened, or the socket could not bind to
the specified port or address. So you have catch or re-throw this checked exception.

The key methods of the DatagramSocket include:

 send(DatagramPacket p): sends a datagram packet.

 receive(DatagramPacket p): receives a datagram packet.

 setSoTimeout(int timeout): sets timeout in milliseconds, limiting the waiting time when receiving data. If
the timeout expires, a SocketTimeoutException is raised.

 close(): closes the socket.

These methods can throw IOException, PortUnreachableException, SocketTimeoutException… so you have to


catch or re-throw them. Consult the DatagramSocket Javadoc for full details.
Now, let’s see some sample programs in action.

Pre Lab Questions:


1. What are the types of sockets in Java?
2. What is the use of accept () method of ServerSocket class?
3. How many ports of TCP IP are reserved for specific protocols?
4. How do ports and sockets work?
5. Are UDP sockets bidirectional?
6. How does socket programming work?
7. What are the differences between frames and packets?
8. What does Datagram mean?
9. What is the difference between virtual circuit and datagram?
10. How does socket programming work in Java?

Sample programs:

We will write code for a client program that requests for quotes from a server that implements the Quote of the
Day (QOTD) service - an Internet standard. The following code snippet sends a DatagramPacket to a server
Lab Learning Material II Year/V Sem CS8581-Networks Laboratory
40

specified by hostname and port:


1
String hostname = "djxmmx.net";
2 int port = 17;
3
4 InetAddress address = InetAddress.getByName(hostname);
5 DatagramSocket socket = new DatagramSocket();
6
7 byte[] buffer = new byte[512];
8
9 DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, port);
socket.send(request);
10
As you can see, the buffer has no data because QOTD service doesn’t require a client sends any specific message.
And you have to specify the server’s address and port in the DatagramPacket. So this code just sends a signal to
the server implying that “Hey, I’d like to get a quote from you”.
And the following code snippet receives a DatagramPacket from the server:
1DatagramPacket response = new DatagramPacket(buffer, buffer.length);
2socket.receive(response);
3
4String quote = new String(buffer, 0, response.getLength());
5
6System.out.println(quote);
As you can see, once the socket is opened, receiving a packet is very simple. And the code converts the byte
array to a String to be printed in readable format.
And here is the code of the full client program that parameterizes the hostname and port number, handles
exceptions and gets a quote from the server for every 10 seconds:
1 import java.io.*;
2 import java.net.*;
3
/**
4 * This program demonstrates how to implement a UDP client program.
5 *
6 *
7 * @author www.codejava.net
*/
8 public class QuoteClient {
9
10 public static void main(String[] args) {
11 if (args.length < 2) {
12 System.out.println("Syntax: QuoteClient <hostname> <port>");
13 return;
}
14
15 String hostname = args[0];
16 int port = Integer.parseInt(args[1]);
17
18 try {
19 InetAddress address = InetAddress.getByName(hostname);
DatagramSocket socket = new DatagramSocket();
20
21 while (true) {
22
23 DatagramPacket request = new DatagramPacket(new byte[1], 1, address,
24port);
Lab Learning Material II Year/V Sem CS8581-Networks Laboratory
41

25 socket.send(request);
26
27 byte[] buffer = new byte[512];
DatagramPacket response = new DatagramPacket(buffer, buffer.length);
28 socket.receive(response);
29
30 String quote = new String(buffer, 0, response.getLength());
31
32 System.out.println(quote);
33 System.out.println();
34
Thread.sleep(10000);
35 }
36
37 } catch (SocketTimeoutException ex) {
38 System.out.println("Timeout error: " + ex.getMessage());
39 ex.printStackTrace();
40 } catch (IOException ex) {
System.out.println("Client error: " + ex.getMessage());
41 ex.printStackTrace();
42 } catch (InterruptedException ex) {
43 ex.printStackTrace();
44 }
}
45}
46
47
48
49
50
51
52
To test this client program, type the following command:
1java QuoteClient djxmmx.net 17
djxmmx.net is a public QOTD server we can use, and 17 is the port number reserved for QOTD service.
You would see the output something like this:
1"When a stupid man is doing something he is ashamed of, he always declares that it is his
2duty." George Bernard Shaw (1856-1950)
3
"Oh the nerves, the nerves; the mysteries of this machine called man!
4 Oh the little that unhinges it, poor creatures that we are!"
5 Charles Dickens (1812-70)
6
7 In Heaven an angel is nobody in particular." George Bernard Shaw (1856-1950)
If you test this program yourself, you may see different quotes because the server returns random quotes. Press
Ctrl + C to terminate the program.
Java UDP Server Example
The following sample program demonstrates how to implement a server for the above client. The following code
creates a UDP server listening on port 17 and waiting for client’s request:
1DatagramSocket socket = new DatagramSocket(17);
2
byte[] buffer = new byte[256];
3
4DatagramPacket request = new DatagramPacket(buffer, buffer.length);
5socket.receive(request);
Lab Learning Material II Year/V Sem CS8581-Networks Laboratory
42

6
The receive() method blocks until a datagram is received. And the following code sends a DatagramPacket to the
client:
1InetAddress clientAddress = request.getAddress();
2int clientPort = request.getPort();
3
4String data = "Message from server";
buffer = data.getBytes();
5
6DatagramPacket response = new DatagramPacket(buffer, buffer.length, clientAddress,
7clientPort);
8socket.send(response);
As you can see, the server also needs to know client’s address and port to send the DatagramPacket. This
information can be obtained from the DatagramPacket received from the client previously. And a String is
converted to an array of bytes which then can be wrapped in a DatagramPacket.
And the following is a full-featured server program that reads quotes from a text file, and sends a random quote
for every client’s request. The quote file and port number are given as program’s arguments. Here’s the code:
1 import java.io.*;
2 import java.net.*;
import java.util.*;
3
4 /**
5 * This program demonstrates how to implement a UDP server program.
6 *
7 *
*/
8 public class QuoteServer {
9 private DatagramSocket socket;
10 private List<String> listQuotes = new ArrayList<String>();
11 private Random random;
12
13 public QuoteServer(int port) throws SocketException {
socket = new DatagramSocket(port);
14 random = new Random();
15 }
16
17 public static void main(String[] args) {
18 if (args.length < 2) {
System.out.println("Syntax: QuoteServer <file> <port>");
19 return;
20 }
21
22 String quoteFile = args[0];
23 int port = Integer.parseInt(args[1]);
24
25 try {
QuoteServer server = new QuoteServer(port);
26 server.loadQuotesFromFile(quoteFile);
27 server.service();
28 } catch (SocketException ex) {
29 System.out.println("Socket error: " + ex.getMessage());
} catch (IOException ex) {
30 System.out.println("I/O error: " + ex.getMessage());
31 }
32 }
33
Lab Learning Material II Year/V Sem CS8581-Networks Laboratory
43

34 private void service() throws IOException {


35 while (true) {
DatagramPacket request = new DatagramPacket(new byte[1], 1);
36 socket.receive(request);
37
38 String quote = getRandomQuote();
39 byte[] buffer = quote.getBytes();
40
41 InetAddress clientAddress = request.getAddress();
int clientPort = request.getPort();
42
43 DatagramPacket response = new DatagramPacket(buffer, buffer.length,
44clientAddress, clientPort);
45 socket.send(response);
46 }
47 }
48
private void loadQuotesFromFile(String quoteFile) throws IOException {
49 BufferedReader reader = new BufferedReader(new FileReader(quoteFile));
50 String aQuote;
51
52 while ((aQuote = reader.readLine()) != null) {
53 listQuotes.add(aQuote);
}
54
55 reader.close();
56 }
57
58 private String getRandomQuote() {
59 int randomIndex = random.nextInt(listQuotes.size());
60 String randomQuote = listQuotes.get(randomIndex);
return randomQuote;
61 }
62}
63
64
65
66
67
68
69
70
71
72
73
Suppose we have a Quotes.txt file with the following content (each quote is in a single line):
1Whether you think you can or you think you can't, you're right - Henry Ford
2There are no traffic jams along the extra mile - Roger Staubach
Build your own dreams, or someone else will hire you to build theirs - Farrah Gray
3What you do today can improve all your tomorrows - Ralph Marston
4Remember that not getting what you want is sometimes a wonderful stroke of luck - Dalai
5Lama

Output:

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


44

Type the following command to run the server program:


1java QuoteServer Quotes.txt 17
And run the client program (on the same computer):
1java QuoteClient localhost 17
Both the client and server are running in an infinite loop, so you have to press Ctrl + C to terminate.
That’s the lesson about how to develop a network client/server application relying on UDP protocol. Based on
this knowledge, you are able to develop client programs that communicate with servers via UDP, and developing
your own UDP client/server applications.

Student Exercise:
1. Write a java code to display the domain name when an ip address is given and vice versa?

Viva Questions:

1. What is UDP socket in Java?


2. What is DNS in Java?
3. Which classes are used for connection less socket programming?
4. How do UDP sockets work?
5. What is difference between TCP and UDP socket?
6. What is socket in TCP and UDP?
7. What is the difference between datagram and packet?
8. What protocol is used by DNS name servers?
9. What is DNS name example?
10. Which language is best for socket programming?

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


45

EX No 5 Simulation of ARP /RARP protocols

Procedure:

Client

1. Start the program


2. Using socket connection is established between client and server.
3. Get the IP address to be converted into MAC address.
4. Send this IP address to server.
5. Server returns the MAC address to client.

Server

1. Start the program


2. Accept the socket which is created by the client.
3. Server maintains the table in which IP and corresponding MAC addresses are stored.
4. Read the IP address which is send by the client.
5. Map the IP address with its MAC address and return the MAC address to client.

Pre Lab Learning Material:

1. Address Resolution Protocol (ARP) –

Address Resolution Protocol is a communication protocol used for discovering physical address associated with
given network address. Typically, ARP is a network layer to data link layer mapping process, which is used to
discover MAC address for given Internet Protocol Address.
In order to send the data to destination, having IP address is necessary but not sufficient; we also need the
physical address of the destination machine. ARP is used to get the physical address (MAC address) of
destination machine.

Before sending
the IP packet,
the MAC
address of
destination
must be

known. If not so, then


sender broadcasts the
ARP-discovery packet
requesting the MAC
Lab Learning Material II Year/V Sem CS8581-Networks Laboratory
46

address of intended destination. Since ARP-discovery is broadcast, every host inside that network will get this
message but the packet will be discarded by everyone except that intended receiver host whose IP is associated.
Now, this receiver will send a unicast packet with its MAC address (ARP-reply) to the sender of ARP-discovery
packet. After the original sender receives the ARP-reply, it updates ARP-cache and start sending unicast message
to the destination.

2. Reverse Address Resolution Protocol (RARP) –

Reverse ARP is a networking protocol used by a client machine in a local area network to request its
Internet Protocol address (IPv4) from the gateway-router’s ARP table. The network administrator creates a table
in gateway-router, which is used to map the MAC address to corresponding IP address. When a new machine is
setup or any machine which don’t have memory to store IP address, needs an IP address for its own use. So the
machine sends a RARP broadcast packet which contains its own MAC address in both sender and receiver
hardware address field.

A special host configured inside the local area network, called as RARP-server is responsible to reply for
these kind of broadcast packets. Now the RARP server attempt to find out the entry in IP to MAC address
mapping table. If any entry matches in table, RARP server sends the response packet to the requesting device
along with IP address.

 LAN technologies like Ethernet, Ethernet II, Token Ring and Fiber Distributed Data Interface (FDDI)
support the Address Resolution Protocol.
 RARP is not being used in today’s networks. Because we have much great featured protocols like
BOOTP (Bootstrap Protocol) and DHCP( Dynamic Host Configuration Protocol).

3. Inverse Address Resolution Protocol (InARP) –

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


47

Instead of using Layer-3 address (IP address) to find MAC address, Inverse ARP uses MAC address to
find IP address. As the name suggests, InARP is just inverse of ARP. Reverse ARP has been replaced by BOOTP
and later DHCP but Inverse ARP is solely used for device configuration. Inverse ARP is enabled by default in
ATM(Asynchronous Transfer Mode) networks. InARP is used to find Layer-3 address from Layer-2 address
(DLCI in frame relay). Inverse ARP dynamically maps local DLCIs to remote IP addresses when you configure
Frame Relay. When using inverse ARP, we know the DLCI of remote router but don’t know its IP address.
InARP sends a request to obtain that IP address and map it to the Layer-2 frame-relay DLCI.

Pre Lab
Questions:

1. What are
ARP and RARP
protocols?
2. Where is
RARP protocol
used?
3. What is the
difference between
ARP and Reverse
ARP?
4. In which
layer does ARP and
RARP operate?
5. How does
ARP work in Layer
3?
6. What is
ARP and its types?

Sample programs:

/ Socket Programming
// ARP and RARP Protocol
// arp_rarp.java

/*
This program automatically creates a file with the IP address of machines, their MAC address and type.
Lab Learning Material II Year/V Sem CS8581-Networks Laboratory
48

ARP protocol is simulated by reading an IP address and returning the MAC address. RARP protocol is simulated
by reading an MAC address and returning the IP address

The program can be extended to read an IP Address / Mac Address and a message and send a packet to the
specified machine using TCP / IP or Datagram sockets
*/

import java.io.*;
import java.util.*;

public class arp_rarp


{
private static final String Command = "arp -a";

public static void getARPTable(String cmd) throws Exception


{
File fp = new File("ARPTable.txt");
FileWriter fw = new FileWriter(fp);

BufferedWriter bw = new BufferedWriter(fw);

Process P = Runtime.getRuntime().exec(cmd);
Scanner S = new Scanner(P.getInputStream()).useDelimiter("\\A");

while(S.hasNext())
bw.write(S.next());

bw.close();
fw.close();
}

public static void findMAC(String ip) throws Exception


{
File fp = new File("ARPTable.txt");
FileReader fr = new FileReader(fp);
BufferedReader br = new BufferedReader(fr);

String line;

while ((line = br.readLine()) != null)


{
if (line.contains(ip))
{
System.out.println("Internet Address Physical Address Type");
System.out.println(line);
break;
}
Lab Learning Material II Year/V Sem CS8581-Networks Laboratory
49

}
if((line == null))
System.out.println("Not found");

fr.close();
br.close();
}

public static void findIP(String mac) throws Exception


{
File fp = new File("ARPTable.txt");
FileReader fr = new FileReader(fp);
BufferedReader br = new BufferedReader(fr);

String line;

while ((line = br.readLine()) != null)


{
if (line.contains(mac))
{
System.out.println("Internet Address Physical Address Type");
System.out.println(line);
break;
}
}

if((line == null))
System.out.println("Not found");

fr.close();
br.close();
}

public static void main(String as[]) throws Exception


{
getARPTable(Command);

Scanner S = new Scanner(System.in);

System.out.println("ARP Protocol.");
System.out.print("Enter IP Address: ");
String IP = S.nextLine();
findMAC(IP);

System.out.println("RARP Protocol.");
System.out.print("Enter MAC Address: ");
String MAC = S.nextLine();
findIP(MAC);
}
Lab Learning Material II Year/V Sem CS8581-Networks Laboratory
50

Output:

>javac arp_rarp.java
>java arp_rarp
ARP Protocol.
Enter IP Address: 10.0.15.253
Internet Address Physical Address Type
10.0.15.253 00-16-76-bd-41-27 dynamic

RARP Protocol.
Enter MAC Address: 01-00-5e-00-00-fc
Internet Address Physical Address Type
224.0.0.252 01-00-5e-00-00-fc static

>java arp_rarp
ARP Protocol.
Enter IP Address: 10.0.15.121
Not found

RARP Protocol.
Enter MAC Address: 01-00-5e-00-00-ff
Not found

D:\cnlab> ARPTable.txt

Interface: 10.0.15.202 --- 0x3


Internet Address Physical Address Type
10.0.15.1 54-78-1a-1e-6a-4f dynamic
10.0.15.72 00-13-20-b7-49-c9 dynamic
10.0.15.253 00-16-76-bd-41-27 dynamic
10.0.15.255 ff-ff-ff-ff-ff-ff static
224.0.0.22 01-00-5e-00-00-16 static
224.0.0.251 01-00-5e-00-00-fb static
224.0.0.252 01-00-5e-00-00-fc static
239.255.255.250 01-00-5e-7f-ff-fa static

Student Exercise:

1. Write a java program to display physical address for the given logical address.

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


51

Viva Questions:

1. What is the difference between ARP and RARP?


2. What is ARP RARP table?
3. What is RARP command?
4. What are ARP packets?
5. What is an ARP table?
6. What is the primary purpose of ARP?

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


52

EX NO: 6 STUDY OF NETWORK SIMULATOR (NS)

Procedure
1. Download and Extract ns2.
2. Building the dependencies.
3. Install ns2 using this code

sudo su cd ~/ns-allinone-2.35/./install

4. Setting the environment path

5. sudo gedit ~/.bashrc

6. Running ns2
Ns

Prelab Learning Material


Network Simulator (Version 2), widely known as NS2, is simply an event driven simulation tool that has
proved 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. Due to its flexibility and modular nature, NS2 has gained constant popularity in the networking
research community since its birth in 1989. Ever since, several revolutions and revisions have marked the
growing maturity of the tool, thanks to substantial contributions from the players in the field. Among these are
the University of California and Cornell University who developed the REAL network simulator,1 the foundation
which NS is based on. Since 1995 the Defense Advanced Research Projects Agency (DARPA) supported
development of NS through the Virtual Inter Network Testbed (VINT) project. Currently the National Science
Foundation (NSF) has joined the ride in development. Last but not the least, the group of Researchers and
developers in the community are constantly working to keep NS2 strong and versatile.

BASIC ARCHITECTURE:

Figure 2.1 shows the basic architecture of NS2. NS2 provides users with executable command ns which
Lab Learning Material II Year/V Sem CS8581-Networks Laboratory
53

takes on input argument, the name of a Tcl simulation scripting file. Users are feeding the name of a Tcl
simulation script (which sets up a simulation) as an input argument of an NS2 executable command ns.

In most cases, a simulation trace file is created, and is used to plot graph and/or to create animation. NS2
consists of two key languages: C++ and Object-oriented Tool Command Language (OTcl). While the C++
defines the internal mechanism (i.e., a backend) of the simulation objects, the OTcl sets up simulation by
assembling and configuring the objects as well as scheduling discrete events (i.e., a frontend).

The C++ and the OTcl are linked together using TclCL. Mapped to a C++ object, variables in the OTcl
domains are sometimes referred to as handles. Conceptually, a handle (e.g., n as a Node handle) is just a string
(e.g.,_o10) in the OTcl domain, and does not contain any functionality. Instead, the functionality (e.g., receiving
a packet) is defined in the mapped C++ object (e.g., of class Connector). In the OTcl domain, a handle acts as a
frontend which interacts with users and other OTcl objects. It may defines its own procedures and variables to
facilitate the interaction. Note that the member procedures and variables in the OTcl domain are called instance
procedures (instprocs) and instance variables (instvars), respectively. Before proceeding further, the readers are
encouraged to learn C++ and OTcl languages. We refer the readers to [14] for the detail of C++, while a brief
tutorial of Tcl and OTcl tutorial are given in Appendices A.1 and A.2, respectively.

NS2 provides a large number of built-in C++ objects. It is advisable to use these C++ objects to set up a
simulation using a Tcl simulation script. However, advance users may find these objects insufficient. They need
to develop their own C++ objects, and use a OTcl configuration interface to put together these objects. After
simulation, NS2 outputs either text-based or animation-based simulation results. To interpret these results
graphically and interactively, tools such as NAM (Network AniMator) and XGraph are used. To analyze a
particular behaviour of the network, users can extract a relevant subset of text-based data and transform it to a
more conceivable presentation.

CONCEPT OVERVIEW:

NS uses two languages because simulator has two different kinds of things it needs to do. On one
hand,detailed simulations of protocols requires a systems programming language which can efficiently
manipulate bytes, packet headers, and implement algorithms that run over large data sets. For these tasks run-
time speed is important and turn-around time (run simulation, find bug, fix bug, recompile, re-run) is less
important. On the other hand, a large part of network research involves slightly varying parameters or
configurations, or quickly exploring a number of scenarios.

In these cases, iteration time (change the model and re-run) is more important. Since configuration runs
once (at the beginning of the simulation), run-time of this part of the task is less important. ns meets both of these
needs with two languages, C++ and OTcl.

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!
Lab Learning Material II Year/V Sem CS8581-Networks Laboratory
54

Variables Command Substitution


set a 5 set len [string length foobar]
set b $a set len [expr [string length foobar] + 9]

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

#Open the Trace file


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 dta 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.
Lab Learning Material II Year/V Sem CS8581-Networks Laboratory
55

Define a “finish‟ procedure


Proc finish { } {
global ns tracefile1 namfile
$ns flush-trace
Close $tracefile1
Close $namfile
Exec nam out.nam &
Exit 0
}
Definition of a network of links and nodes
The way to define a node is

set n0 [$ns node]


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. We
should also define the buffer capacity of the queue related to each link. An example would be:

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


$ns queue-limit $n0 $n2 20
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
Lab Learning Material II Year/V Sem CS8581-Networks Laboratory
56

$udp set fid_2


#setup a CBR over UDP connection

The below 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.

set cbr [new Application/Traffic/CBR]


$cbr attach-agent $udp
$cbr set packetsize_ 100
$cbr set rate_ 0.01Mb
$cbr set random_ false

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.

VIVA QUESTIONS:
1. What protocols does ns support?
2. What Is Simulation?
3. Define Network
4. What is meant by Protocol?
5. What are the constituent parts of NS2?

RESULT:

Thus the Network Simulator 2 is studied in detail.

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


57

Simulation of Congestion control Algorithms using NS

Procedure

1. Read The Data For Packets


2. Read The Queue Size
3. Divide the Data into Packets
4. Assign the random Propagation delays for each packets to input into the bucket (input_packet).
5. wlile((Clock++< total_paclets))
a. if (clock == input_packet) i. insert into Queue
b. if (clock % 5 == 0 ) i. Remove paclet from Queue
6. End

Prelab Learning Material


Wireless Ad hoc routing, mobile IP, sensor-MAC Tracing, visualization and various utilities NS(Network
Simulators)
Most of the commercial simulators are GUI driven, while some network simulators are CLI driven. The
network model / configuration describes the state of the network (nodes, routers, switches, links) and the events
(data transmissions, packet error etc.). An important output of simulations are the trace files. Trace files log every
packet, every event that occurred in the simulation and are used for analysis. Network simulators can also provide
other tools to facilitate visual analysis of trends and potential trouble spots.
Most network simulators use discrete event simulation, in which a list of pending "events" is stored, and
those events are processed in order, with some events triggering future events— such as the event of the arrival
of a packet at one node triggering the event of the arrival of that packet at a downstream node.
Simulation of networks is a very complex task. For example, if congestion is high, then estimation of the
average occupancy is challenging because of high variance. To estimate the likelihood of a buffer overflow in a
network, the time required for an accurate answer can be extremely large. Specialized techniques such as "control
variates" and "importance sampling" have been developed to speed simulation.
Examples of network simulators
There are many both free/open-source and proprietary network simulators. Examples of
notable network simulation software are, ordered after how often they are mentioned in research papers:
1. ns (open source)
2. OPNET (proprietary software)
3. NetSim (proprietary software)
Uses of network simulators
Network simulators serve a variety of needs. Compared to the cost and time involved in setting up an
entire test bed containing multiple networked computers, routers and data links, network simulators are relatively
fast and inexpensive. They allow engineers, researchers to test scenarios that might be particularly difficult or
expensive to emulate using real hardware - for instance, simulating a scenario with several nodes or
experimenting with a new protocol in the network.
Network simulators are particularly useful in allowing researchers to test new networking protocols or
changes to existing protocols in a controlled and reproducible environment. A typical network simulator
encompasses a wide range of networking technologies and can help the users to build complex networks from
basic building blocks such as a variety of nodes and links.
With the help of simulators, one can design hierarchical networks using various types of nodes like
computers, hubs, bridges, routers, switches, links, mobile units etc. Various types of Wide Area Network (WAN)
technologies like TCP, ATM, IP etc. and Local Area Network (LAN) technologies like Ethernet, token rings etc.,
can all be simulated with a typical simulator and the user can test, analyze various standard results apart from
Lab Learning Material II Year/V Sem CS8581-Networks Laboratory
58

devising some novel protocol or strategy for routing etc. Network simulators are also widely used to imulate
battlefield networks in Network-centric warfare There are a wide variety of network simulators, ranging from the
very simple to the very complex. Minimally, a network simulator must enable a user to represent a network
topology, specifying the nodes on the network, the links between those nodes and the traffic between the nodes.

More complicated systems may allow the user to specify everything about the protocols used to handle
traffic in a network. Graphical applications allow users to easily visualize the workings of their simulated
environment. Text-based applications may provide a less intuitive interface, but may permit more advanced
forms of customization.

Packet loss
PL occurs when one or more packets of data travelling across a computer network fail to reach their
destination. Packet loss is distinguished as one of the three main error types encountered in digital
communications; the other two being bit error and spurious packets caused due to noise. Packets can be lost in a
network because they may be dropped when a queue in the network node overflows. The amount of packet loss
during the steady state is another important property of a congestion control scheme.
The larger the value of packet loss, the more difficult it is for transport layer protocols to maintain high
bandwidths, the sensitivity to loss of individual packets, as well as to frequency and patterns of loss among
longer packet sequences is strongly dependent on the application itself.

Throughput
This is the main performance measure characteristic, and most widely used. In communication networks, such as
Ethernet or packet radio, throughput or network throughput is the average rate of successful message delivery
over a communication channel. The throughput is usually measured in bits per second (bit/s or bps), and
sometimes in data packet per second or data packets per time slot This measure how soon the receiver is able to
get a certain amount of data send by the sender. It is determined as the ratio of the total data received to the end to
end delay. Throughput is an important factor which directly impacts the network performance
Delay
Delay is the time elapsed while a packet travels from one point e.g., source premise or network ingress to
destination premise or network degrees. The larger the value of delay, the more difficult it is for transport layer
protocols to maintain high bandwidths. We will calculate end to end delay
Queue Length
A queuing system in networks can be described as packets arriving for service, waiting for service if it is not
immediate, and if having waited for service, leaving the system after being served. Thus queue length is very
important characteristic to determine that how well the active queue management of the congestion control
algorithm has been working.

Prelab Questions

1. What is congestion control in network?


2. Why congestion control is an important activity of networking?
3. What is open loop congestion control?
4. What is congestion explain approaches to congestion control?
5. How does TCP implement congestion control?
6. What is the difference between flow control and congestion control?

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


59

Sample Program

import java.util.*;
public class leaky
{
static int min(int x,int y)
{
if(x<y)
return x;
else
return y;
}
public static void main(String[] args)
{ int drop=0,mini,nsec,cap,count=0,i,process;
int inp[]=new int[25];
Scanner sc=new Scanner(System.in);
System.out.println("Enter The Bucket Size\n");
cap= sc.nextInt();
System.out.println("Enter The Operation Rate\n");
process= sc.nextInt();
System.out.println("Enter The No. Of Seconds You Want To Stimulate\n");
nsec=sc.nextInt();
for(i=0;i<nsec;i++)
{ System.out.print("Enter The Size Of The Packet Entering At "+ i+1 + "
sec");
inp[i] = sc.nextInt();
}
System.out.println("\nSecond | Packet Recieved | Packet Sent | Packet Left |
Packet Dropped|\n");
System.out.println("----------------------------------------------------------------------\n");
for(i=0;i<nsec;i++)
{ count+=inp[i];
if(count>cap)
{ drop=count-cap;
count=cap;
}
System.out.print(i+1);
System.out.print("\t\t"+inp[i]);
mini=min(count,process);
System.out.print("\t\t"+mini);
count=count-mini;
System.out.print("\t\t"+count);
System.out.print("\t\t"+drop);
drop=0;
System.out.println();
}
for(;count!=0;i++)
{
if(count>cap)
Lab Learning Material II Year/V Sem CS8581-Networks Laboratory
60

{
drop=count-cap;
count=cap;
}
System.out.print(i+1);
System.out.print("\t\t0");
mini=min(count,process);
System.out.print("\t\t"+mini);
count=count-mini;
System.out.print("\t\t"+count);
System.out.print("\t\t"+drop);
System.out.println();
}
}
}

Output:
Enter The Bucket Size
5
Enter The Operation Rate
2
Enter The No. Of Seconds You Want To Stimulate
3
Enter The Size Of The Packet Entering At 1 sec
5
Enter The Size Of The Packet Entering At 1 sec
4
Enter The Size Of The Packet Entering At 1 sec
3
Second|Packet Recieved|Packet Sent|Packet Left|Packet Dropped|
---------------------------------------------------------------------------------
15230
24232
33231
40210
5010
Viva Questions
1. What is flow control in computer networks?
2. Does UDP provide congestion control?
3. Does IP have congestion control?
4. How does TCP provide flow control and reliability?
5. What is congestion control in networking?
6. Why is congestion control important?
7. What is congestion window?
8. What causes network congestion?
Lab Learning Material II Year/V Sem CS8581-Networks Laboratory
61

ExNo.7 Study of TCP/UDP Performance Using Simulation Tool

Procedure

UDP Performance
1. Start network simulator OTCL editor.
2. Create new simulator using set ns [new Simulator] syntax
3: Create procedure to trace all path
proc finish {} {
global ns nf tf
$ns flush-trace
close $nf
close $tf
exec nam tcp.nam &
exit 0}
4: Connect with TCP and SINK command.
$ns connect $tcp $sink
5: Run and Execute the program.
$ns run

TCP Performance

1: Start network simulator OTCL editor.


2: Create new simulator using set ns [new Simulator] syntax
3: Create Trace route to Network Animator
set nf [open out.nam w]
$ns namtrace-all $nf
4: Create procedure to trace all path
proc finish {} {
global ns nf
$ns flush-trace
#Close the NAM trace file
close $nf
#Execute NAM on the trace file
exec nam out.nam &
exit 0
}
5: Connect with TCP and SINK command.
$ns connect $tcp $sink
6: Setup a FTP over TCP connection
set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ftp set type_ FTP
7: Setup a CBR over UDP connection
set cbr [new Application/Traffic/CBR]
$cbr attach-agent $udp

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


62

$cbr set type_ CBR


8: Run and Execute the program.
$ns run

Prelab learning Material

UDP performance

 Latency is the time required to transmit a packet across a network:


o Latency may be measured in many different ways: round trip, one way, etc.
o Latency may be impacted by any element in the chain which is used to transmit data: workstation,
WAN links, routers, local area network (LAN), server,… and ultimately it may be limited, in the
case of very large networks, by the speed of light.
 Throughput is defined as the quantity of data being sent/received by unit of time
 Packet loss reflects the number of packets lost per 100 packets sent by a host

TCP performance

 The TCP connection setup handshake


 TCP slow-start congestion control
 Nagle’s algorithm for data aggregation
 TCP’s delayed acknowledgment algorithm for piggybacked acknowledgments
 TIME_WAIT delays and port exhaustion

Sample Program:

UDP Performance
set ns [new Simulator]
set nf [open tcp.nam w]
$ns namtrace-all $nf
set tf [open out.tr w]
$ns trace-all $tf
proc finish {} {
global ns nf tf
$ns flush-trace
close $nf
close $tf
exec nam tcp.nam &
exit 0
}
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
Lab Learning Material II Year/V Sem CS8581-Networks Laboratory
63

set n4 [$ns node]


set n5 [$ns node]
$ns duplex-link $n0 $n4 1Mb 50ms DropTail
$ns duplex-link $n1 $n4 1Mb 50ms DropTail
$ns duplex-link $n2 $n5 1Mb 1ms DropTail
$ns duplex-link $n3 $n5 1Mb 1ms DropTail
$ns duplex-link $n4 $n5 1Mb 50ms DropTail
$ns duplex-link-op $n4 $n5 queuePos 0.5
set tcp [new Agent/TCP]
$ns attach-agent $n0 $tcp
set sink [new Agent/TCPSink]
$ns attach-agent $n2 $sink
$ns connect $tcp $sink
set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ns at 0.0 "$ftp start"
$ns at 2.5 "$ftp stop"
$ns at 3 "finish"
$ns run

TCP Performance

#Create a simulator object


set ns [new Simulator]
#Define different colors for data flows (for NAM)
$ns color 1 Blue
$ns color 2 Red
#Open the NAM trace file
set nf [open out.nam w]
$ns namtrace-all $nf
#Define a 'finish' procedure
proc finish {} {
global ns nf
$ns flush-trace
#Close the NAM trace file
close $nf
#Execute NAM on the trace file
exec nam out.nam &
exit 0
}
#Create four nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
#Create links between the nodes
$ns duplex-link $n0 $n2 2Mb 10ms DropTail
Lab Learning Material II Year/V Sem CS8581-Networks Laboratory
64

$ns duplex-link $n1 $n2 2Mb 10ms DropTail


$ns duplex-link $n2 $n3 1.7Mb 20ms DropTail
#Set Queue Size of link (n2-n3) to 10
$ns queue-limit $n2 $n3 10
#Give node position (for NAM)
$ns duplex-link-op $n0 $n2 orient right-down
$ns duplex-link-op $n1 $n2 orient right-up
$ns duplex-link-op $n2 $n3 orient right
#Monitor the queue for link (n2-n3). (for NAM)
$ns duplex-link-op $n2 $n3 queuePos 0.5
#Setup a TCP connection
set tcp [new Agent/TCP]
$tcp set class_ 2
$ns attach-agent $n0 $tcp
set sink [new Agent/TCPSink]
$ns attach-agent $n3 $sink
$ns connect $tcp $sink
$tcp set fid_ 1
#Setup a FTP over TCP connection
set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ftp set type_ FTP
#Setup a UDP connection
set udp [new Agent/UDP]
$ns attach-agent $n1 $udp
set null [new Agent/Null]
$ns attach-agent $n3 $null
$ns connect $udp $null
$udp set fid_ 2
#Setup a CBR over UDP connection
set cbr [new Application/Traffic/CBR]
$cbr attach-agent $udp
$cbr set type_ CBR
$cbr set packet_size_ 1000
$cbr set rate_ 1mb
$cbr set random_ false
#Schedule events for the CBR and FTP agents
$ns at 0.1 "$cbr start"
$ns at 1.0 "$ftp start"
$ns at 4.0 "$ftp stop"
$ns at 4.5 "$cbr stop"
#Detach tcp and sink agents (not really necessary)
$ns at 4.5 "$ns detach-agent $n0 $tcp ; $ns detach-agent $n3 $sink"
#Call the finish procedure after 5 seconds of simulation time
$ns at 5.0 "finish"
#Print CBR packet size and interval
puts "CBR packet size = [$cbr set packet_size_]"
puts "CBR interval = [$cbr set interval_]"
#Run the simulation $ns run
Lab Learning Material II Year/V Sem CS8581-Networks Laboratory
65

Prelab Questions

1. Which one of the following is part of TCP protocol?


2. Which layer would the Transmission Control Protocol TCP be in?
3. What are the 4 TCP IP layers?
4. What is TCP connection?
5. Which protocol does not use TCP?
6. What is the main difference between TCP and UDP?
7. What is UDP protocol?
8. How does UDP protocol work?

Viva Questions
1. Does YouTube use UDP?
2. What layer is UDP?
3. Is UDP still used?
4. Which is better TCP or UDP?
5. Why UDP is needed?
6. Which protocol is used for end to end delivery?
7. What is meant by end to end delivery?
8. Why are transport layer services called end to end?
9. Does Netflix use UDP?
10. Does DNS use TCP or UDP?

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


66

Ex.No 8 Simulation of Distance Vector Routing Algorithm

Procedure:

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.

Pre Lab Learning Material

o The Distance vector algorithm is iterative, asynchronous and distributed.


o Distributed: It is distributed in that each node receives information from one or more of its
directly attached neighbors, performs calculation and then distributes the result back to its
neighbors.
o Iterative: It is iterative in that its process continues until no more information is available to be
exchanged between neighbors.
o Asynchronous: It does not require that all of its nodes operate in the lock step with each other.
o The Distance vector algorithm is a dynamic algorithm.
o It is mainly used in ARPANET, and RIP.
o Each router maintains a distance table known as Vector

Three Keys to understand the working of Distance Vector Routing Algorithm:


o Knowledge about the whole network: Each router shares its knowledge through the entire network. The
Router sends its collected knowledge about the network to its neighbors.
o Routing only to neighbors: The router sends its knowledge about the network to only those routers
which have direct links. The router sends whatever it has about the network through the ports. The
information is received by the router and uses the information to update its own routing table.
o Information sharing at regular intervals: Within 30 seconds, the router sends the information to the
neighboring routers.

Distance Vector Routing Algorithm

Let dx(y) be the cost of the least-cost path from node x to node y. The least costs are related by Bellman-Ford
equation,

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


67

dx(y) = minv{c(x,v) + dv(y)}

Where the minv is the equation taken for all x neighbors. After traveling from x to v, if we consider the least-
cost path from v to y, the path cost will be c(x,v)+dv(y). The least cost from x to y is the minimum of c(x,v)+dv(y)
taken over all neighbors.

With the Distance Vector Routing algorithm, the node x contains the following routing information:

o For each neighbor v, the cost c(x,v) is the path cost from x to directly attached neighbor, v.
o The distance vector x, i.e., Dx = [ Dx(y) : y in N ], containing its cost to all destinations, y, in N.
o The distance vector of each of its neighbors, i.e., Dv = [ Dv(y) : y in N ] for each neighbor v of x.

Distance vector routing is an asynchronous algorithm in which node x sends the copy of its distance vector to
all its neighbors. When node x receives the new distance vector from one of its neighboring vector, v, it saves the
distance vector of v and uses the Bellman-Ford equation to update its own distance vector. The equation is given
below:

dx(y) = minv{ c(x,v) + dv(y)} for each node y in N

The node x has updated its own distance vector table by using the above equation and sends its updated table to
all its neighbors so that they can update their own distance vectors.

Pre Lab Questions:

1. What are the three main elements of distance vector routing algorithm?

2. What is distance vector routing in networking?

3. What is the count to infinity problem in distance vector routing?

4. Is OSPF a distance vector protocol?

5. What is the difference between distance vector and link state routing protocols?

Sample Exercise

To simulate and study the Distance Vector routing algorithm using simulation.

Source Code:
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 { } {
Lab Learning Material II Year/V Sem CS8581-Networks Laboratory
68

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

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


69

$ns at 45 "finish"
$ns run

OUTPUT:

Student Exercise:

1. Simulate and study the Link State routing algorithm using simulation.

Viva Questions:

1. What is link state routing algorithm?

2. What is distance vector protocols?

3. What is Link State Algorithm?

4. Is distance vector or scalar?

5. What is Cisco's proprietary routing protocol?

6. Why is rip a distance vector routing protocol?

7. What is the time complexity of Bellman Ford algorithm?

8. Can increasing the routing cost of a link cause the count to infinity problem?

9. Why OSPF is link state protocol?

10. Is OSPF Classful or classless?

11. How does OSPF prevent loops?

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


70

EX NO:9 Performance Evaluation of Routing Protocols using Simulation Tool

Procedure (AODV Routing Protocol)

1. In the TCL script, when the user configures AODV as a routing protocol by using the command,$ns node-
config -adhocRouting AODV the pointer moves to the “start” and this “start” moves the pointer to the
Command function of AODVprotocol.
2. In the Command function, the user can find two timers in the “start”
* btimer.handle((Event*) 0);
* htimer.handle((Event*) 0);

3. Let’s consider the case of htimer, the flow points toHelloTimer::handle(Event*) function and the user
can see the following lines:
agent -> sendHello();
double interval = MinHelloInterval + ((MaxHelloInterval - Min-HelloInterval) *
Random::uniform());
assert(interval -> = 0);
Scheduler::instance().schedule(this, &intr, interval);
These lines are calling the sendHello() function by setting the appropriate interval of Hello Packets.

4. Now, the pointer is in AODV::sendHello() function and the user can


seeScheduler::instance().schedule(target , p, 0.0) which will schedule the packets.

5. In the destination node AODV::recv(Packet*p, Handler*) is called, but actually this is done after the
node is receiving a packet.

6. AODV::recv(Packet*p, Handler*) function then calls therecvAODV(p) function.

7. Hence, the flow goes to the AODV::recvAODV(Packet *p) function, which will check different packets
types and call the respective function.

8. In this example, flow can go to case


AODVTYPE HELLO:
recvHello(p);
break;

9. Finally, in the recvHello() function, the packet is received.


Here you can download the following tcl file of aodv protocol simple-wireless.tcl

Pre-Lab Learning Material:

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


71

The reactive on demand routing protocols establish the route to a particular destination only if it is
needed. Adhoc on-demand Distance Vector (AODV) is one of the commonly used reactive on demand routing
protocols in mobile ad hoc network (MANET). AODV is a reactive enhancement of the DSDV protocol. The
route discovery process involves ROUTE REQUEST (RREQ) and ROUTE REPLY (RREP) packets. The source
node initiates the route requested through the route discovery process using RREQ packets. The generated route
request is forwarded to the neighbors of the source node and this process is repeated till it reaches the destination.
On receiving a RREQ packet, an intermediate node with route to destination, it generates a RREP containing the
number of hops required to reach the destination.

All intermediate nodes that participates in relaying this reply to the source node creates a forward route to
destination. AODV minimizes the number of packets involved in route discovery by establishing routes on-
demand. The sample15.tcl shows a node configuration for a wireless mobile node that runs AODV as its adhoc
routing protocol. Prior to the establishment of communication between the source and receiver node, the routing
protocol should be mentioned to find the route between them. Data Transmission is established between nodes
using UDP agent and CBR traffic.

Pre-Lab Questions:

1. What is Aodv routing protocol in ns2?

2. What is ad hoc routing protocols?

3. What is Aodv and DSDV?

4. What is DSDV routing protocol?

5. What is black hole attack?


Sample Exercise:
Evaluate the performance of AODV routing protocol using simulation tool.

Source Code:

### Setting The Simulator Objects

set ns_ [new Simulator]


#create the nam and trace file:
set tracefd [open aodv.tr w]
$ns_ trace-all $tracefd

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


72

set namtrace [open aodv.nam w]


$ns_ namtrace-all-wireless $namtrace $val(x) $val(y)

set topo [new Topography]


$topo load_flatgrid $val(x) $val(y)
create-god $val(nn)
set chan_1_ [new $val(chan)]

#### Setting The Distance Variables

# For model 'TwoRayGround'


set dist(5m) 7.69113e-06
set dist(9m) 2.37381e-06
set dist(10m) 1.92278e-06
set dist(11m) 1.58908e-06
set dist(12m) 1.33527e-06
set dist(13m) 1.13774e-06
set dist(14m) 9.81011e-07
set dist(15m) 8.54570e-07
set dist(16m) 7.51087e-07
set dist(20m) 4.80696e-07
set dist(25m) 3.07645e-07
set dist(30m) 2.13643e-07
set dist(35m) 1.56962e-07
set dist(40m) 1.56962e-10
set dist(45m) 1.56962e-11
set dist(50m) 1.20174e-13
Phy/WirelessPhy set CSThresh_ $dist(50m)
Phy/WirelessPhy set RXThresh_ $dist(50m)

# Defining Node Configuration

$ns_ node-config -adhocRouting $val(rp) \


-llType $val(ll) \
-macType $val(mac) \
-ifqType $val(ifq) \
-ifqLen $val(ifqlen) \
-antType $val(ant) \
-propType $val(prop) \
-phyType $val(netif) \
-topoInstance $topo \
-agentTrace ON \
-routerTrace ON \
-macTrace ON \
-movementTrace ON \
-channel $chan_1_

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


73

### Creating The WIRELESS NODES

set Server1 [$ns_ node]


set Server2 [$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]
set n8 [$ns_ node]
set n9 [$ns_ node]
set n10 [$ns_ node]
set n11 [$ns_ node]
set n12 [$ns_ node]
set n13 [$ns_ node]
set n14 [$ns_ node]
set n15 [$ns_ node]
set n16 [$ns_ node]
set n17 [$ns_ node]
set n18 [$ns_ node]
set n19 [$ns_ node]
set n20 [$ns_ node]
set n21 [$ns_ node]
set n22 [$ns_ node]

set opt(seed) 0.1


set a [ns-random $opt(seed)]
set i 0
while {$i < 5} {
incr i
}

### Setting The Initial Positions of Nodes

$Server1 set X_ 513.0


$Server1 set Y_ 517.0
$Server1 set Z_ 0.0

$Server2 set X_ 1445.0


$Server2 set Y_ 474.0
$Server2 set Z_ 0.0

$n2 set X_ 36.0


$n2 set Y_ 529.0
$n2 set Z_ 0.0

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


74

$n3 set X_ 143.0


$n3 set Y_ 666.0
$n3 set Z_ 0.0

$n4 set X_ 201.0


$n4 set Y_ 552.0
$n4 set Z_ 0.0

$n5 set X_ 147.0


$n5 set Y_ 403.0
$n5 set Z_ 0.0

$n6 set X_ 230.0


$n6 set Y_ 291.0
$n6 set Z_ 0.0

$n7 set X_ 295.0


$n7 set Y_ 419.0
$n7 set Z_ 0.0

$n8 set X_ 363.0


$n8 set Y_ 335.0
$n8 set Z_ 0.0

$n9 set X_ 334.0


$n9 set Y_ 647.0
$n9 set Z_ 0.0

$n10 set X_ 304.0


$n10 set Y_ 777.0
$n10 set Z_ 0.0

$n11 set X_ 412.0


$n11 set Y_ 194.0
$n11 set Z_ 0.0

$n12 set X_ 519.0


$n12 set Y_ 361.0
$n12 set Z_ 0.0

$n13 set X_ 569.0


$n13 set Y_ 167.0
$n13 set Z_ 0.0

$n14 set X_ 349.0


$n14 set Y_ 546.0
$n14 set Z_ 0.0

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


75

$n15 set X_ 466.0


$n15 set Y_ 668.0
$n15 set Z_ 0.0

$n16 set X_ 489.0


$n16 set Y_ 794.0
$n16 set Z_ 0.0

$n17 set X_ 606.0


$n17 set Y_ 711.0
$n17 set Z_ 0.0

$n18 set X_ 630.0


$n18 set Y_ 626.0
$n18 set Z_ 0.0

$n19 set X_ 666.0


$n19 set Y_ 347.0
$n19 set Z_ 0.0

$n20 set X_ 741.0


$n20 set Y_ 152.0
$n20 set Z_ 0.0

$n21 set X_ 882.0


$n21 set Y_ 264.0
$n21 set Z_ 0.0

$n22 set X_ 761.0


$n22 set Y_ 441.0
$n22 set Z_ 0.0

## Giving Mobility to Nodes

$ns_ at 0.75 "$n2 setdest 379.0 349.0 20.0"


$ns_ at 0.75 "$n3 setdest 556.0 302.0 20.0"
$ns_ at 0.20 "$n4 setdest 309.0 211.0 20.0"
$ns_ at 1.25 "$n5 setdest 179.0 333.0 20.0"
$ns_ at 0.75 "$n6 setdest 139.0 63.0 20.0"
$ns_ at 0.75 "$n7 setdest 320.0 27.0 20.0"
$ns_ at 1.50 "$n8 setdest 505.0 124.0 20.0"
$ns_ at 1.25 "$n9 setdest 274.0 487.0 20.0"
$ns_ at 1.25 "$n10 setdest 494.0 475.0 20.0"
$ns_ at 1.25 "$n11 setdest 899.0 757.0 25.0"
$ns_ at 0.50 "$n12 setdest 598.0 728.0 25.0"
$ns_ at 0.25 "$n13 setdest 551.0 624.0 25.0"
$ns_ at 1.25 "$n14 setdest 397.0 647.0 25.0"
$ns_ at 1.25 "$n15 setdest 748.0 688.0 25.0"
$ns_ at 1.25 "$n16 setdest 842.0 623.0 25.0"
Lab Learning Material II Year/V Sem CS8581-Networks Laboratory
76

$ns_ at 1.25 "$n17 setdest 678.0 548.0 25.0"


$ns_ at 0.75 "$n18 setdest 741.0 809.0 20.0"
$ns_ at 0.75 "$n19 setdest 437.0 799.0 20.0"
$ns_ at 0.20 "$n20 setdest 159.0 722.0 20.0"
$ns_ at 1.25 "$n21 setdest 700.0 350.0 20.0"
$ns_ at 0.75 "$n22 setdest 839.0 444.0 20.0"

## Setting The Node Size

$ns_ initial_node_pos $Server1 75


$ns_ initial_node_pos $Server2 75
$ns_ initial_node_pos $n2 40
$ns_ initial_node_pos $n3 40
$ns_ initial_node_pos $n4 40
$ns_ initial_node_pos $n5 40
$ns_ initial_node_pos $n6 40
$ns_ initial_node_pos $n7 40
$ns_ initial_node_pos $n8 40
$ns_ initial_node_pos $n9 40
$ns_ initial_node_pos $n10 40
$ns_ initial_node_pos $n11 40
$ns_ initial_node_pos $n12 40
$ns_ initial_node_pos $n13 40
$ns_ initial_node_pos $n14 40
$ns_ initial_node_pos $n15 40
$ns_ initial_node_pos $n16 40
$ns_ initial_node_pos $n17 40
$ns_ initial_node_pos $n18 40
$ns_ initial_node_pos $n19 40
$ns_ initial_node_pos $n20 40
$ns_ initial_node_pos $n21 40
$ns_ initial_node_pos $n22 40

#### Setting The Labels For Nodes

$ns_ at 0.0 "$Server1 label Server1"


$ns_ at 0.0 "$Server2 label Server2"

#Setting Color For Server

$Server1 color maroon


$ns_ at 0.0 "$Server1 color maroon"

$Server2 color maroon


$ns_ at 0.0 "$Server2 color maroon"

## SETTING ANIMATION RATE


$ns_ at 0.0 "$ns_ set-animation-rate 15.0ms"
Lab Learning Material II Year/V Sem CS8581-Networks Laboratory
77

# COLORING THE NODES


$n9 color blue
$ns_ at 4.71 "$n9 color blue"
$n5 color blue
$ns_ at 7.0 "$n5 color blue"
$n2 color blue
$ns_ at 7.29 "$n2 color blue"

$n16 color blue


$ns_ at 7.59 "$n16 color blue"

$n9 color maroon


$ns_ at 7.44 "$n9 color maroon"

$ns_ at 7.43 "$n9 label TTLover"


$ns_ at 7.55 "$n9 label \"\""

$n12 color blue


$ns_ at 7.85 "$n12 color blue"

#### Establishing Communication

set udp0 [$ns_ create-connection UDP $Server1 LossMonitor $n18 0]


$udp0 set fid_ 1
set cbr0 [$udp0 attach-app Traffic/CBR]
$cbr0 set packetSize_ 1000
$cbr0 set interval_ .07
$ns_ at 0.0 "$cbr0 start"
$ns_ at 4.0 "$cbr0 stop"

set udp1 [$ns_ create-connection UDP $Server1 LossMonitor $n22 0]


$udp1 set fid_ 1
set cbr1 [$udp1 attach-app Traffic/CBR]
$cbr1 set packetSize_ 1000
$cbr1 set interval_ .07
$ns_ at 0.1 "$cbr1 start"
$ns_ at 4.1 "$cbr1 stop"

set udp2 [$ns_ create-connection UDP $n21 LossMonitor $n20 0]


$udp2 set fid_ 1
set cbr2 [$udp2 attach-app Traffic/CBR]
$cbr2 set packetSize_ 1000
$cbr2 set interval_ .07
$ns_ at 2.4 "$cbr2 start"
$ns_ at 4.1 "$cbr2 stop"

set udp3 [$ns_ create-connection UDP $Server1 LossMonitor $n15 0]


$udp3 set fid_ 1
Lab Learning Material II Year/V Sem CS8581-Networks Laboratory
78

set cbr3 [$udp3 attach-app Traffic/CBR]


$cbr3 set packetSize_ 1000
$cbr3 set interval_ 5
$ns_ at 4.0 "$cbr3 start"
$ns_ at 4.1 "$cbr3 stop"

set udp4 [$ns_ create-connection UDP $Server1 LossMonitor $n14 0]


$udp4 set fid_ 1
set cbr4 [$udp4 attach-app Traffic/CBR]
$cbr4 set packetSize_ 1000
$cbr4 set interval_ 5
$ns_ at 4.0 "$cbr4 start"
$ns_ at 4.1 "$cbr4 stop"

set udp5 [$ns_ create-connection UDP $n15 LossMonitor $n16 0]


$udp5 set fid_ 1
set cbr5 [$udp5 attach-app Traffic/CBR]
$cbr5 set packetSize_ 1000
$cbr5 set interval_ 5
$ns_ at 4.0 "$cbr5 start"
$ns_ at 4.1 "$cbr5 stop"

set udp6 [$ns_ create-connection UDP $n15 LossMonitor $n17 0]


$udp6 set fid_ 1
set cbr6 [$udp6 attach-app Traffic/CBR]
$cbr6 set packetSize_ 1000
$cbr6 set interval_ 5
$ns_ at 4.0 "$cbr6 start"
$ns_ at 4.1 "$cbr6 stop"

set udp7 [$ns_ create-connection UDP $n14 LossMonitor $n4 0]


$udp7 set fid_ 1
set cbr7 [$udp7 attach-app Traffic/CBR]
$cbr7 set packetSize_ 1000
$cbr7 set interval_ 5
$ns_ at 4.0 "$cbr7 start"
$ns_ at 4.1 "$cbr7 stop"

set udp8 [$ns_ create-connection UDP $n14 LossMonitor $n9 0]


$udp8 set fid_ 1
set cbr8 [$udp8 attach-app Traffic/CBR]
$cbr8 set packetSize_ 1000
$cbr8 set interval_ 5
$ns_ at 4.0 "$cbr8 start"
$ns_ at 4.1 "$cbr8 stop"

set udp9 [$ns_ create-connection UDP $n4 LossMonitor $n3 0]


$udp9 set fid_ 1
set cbr9 [$udp9 attach-app Traffic/CBR]
Lab Learning Material II Year/V Sem CS8581-Networks Laboratory
79

$cbr9 set packetSize_ 1000


$cbr9 set interval_ 5
$ns_ at 4.0 "$cbr9 start"
$ns_ at 4.1 "$cbr9 stop"

set udp10 [$ns_ create-connection UDP $n4 LossMonitor $n2 0]


$udp10 set fid_ 1
set cbr10 [$udp10 attach-app Traffic/CBR]
$cbr10 set packetSize_ 1000
$cbr10 set interval_ 5
$ns_ at 4.0 "$cbr10 start"
$ns_ at 4.1 "$cbr10 stop"

set udp11 [$ns_ create-connection UDP $n9 LossMonitor $n16 0]


$udp11 set fid_ 1
set cbr11 [$udp11 attach-app Traffic/CBR]
$cbr11 set packetSize_ 1000
$cbr11 set interval_ 5
$ns_ at 4.0 "$cbr11 start"
$ns_ at 4.1 "$cbr11 stop"

set udp12 [$ns_ create-connection UDP $n9 LossMonitor $n10 0]


$udp12 set fid_ 1
set cbr12 [$udp12 attach-app Traffic/CBR]
$cbr12 set packetSize_ 1000
$cbr12 set interval_ 5
$ns_ at 4.0 "$cbr12 start"
$ns_ at 4.1 "$cbr12 stop"

#ANNOTATIONS DETAILS

$ns_ at 0.0 "$ns_ trace-annotate \"MOBILE NODE MOVEMENTS\""


$ns_ at 4.1 "$ns_ trace-annotate \"NODE27 CACHE THE DATA FRO SERVER\""
#$ns_ at 4.59 "$ns_ trace-annotate \"PACKET LOSS AT NODE27\""
$ns_ at 4.71 "$ns_ trace-annotate \"NODE10 CACHE THE DATA\""

### PROCEDURE TO STOP

proc stop {} {

global ns_ tracefd


$ns_ flush-trace
close $tracefd
exec nam datacache.nam &
exit 0

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


80

puts "Starting Simulation........"


$ns_ at 25.0 "stop"
$ns_ run

Student Exercise:
1. Evaluate the performance of DSR Routing protocol using NS2 simulation.
2. Evaluate the performance of DSDV Routing protocol using NS2 simulation.

Viva Questions:

1. What is GREY hole attack?

2. What is black hole attack in WSN?

3. What is wormhole attack?

4. Why do packets get dropped?

5. What are attack packets?

6. What is BGP blackhole?

7. What is DSR routing protocol?

8. What is global state routing?

9. What is routing in wireless networks?

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


81

EX NO : 10 Simulation of Error Correction Code(CRC)

Procedure:

1. Randomly generate an N-bit information stream. You need to set N=8.


2. Using the generator G=1001, generate the CRC bits and derive an (N+3)-bit coded stream.
3. Send the coded stream into a random flipping channel with bit-flip probability p.
Test three cases: p=0.1, p=0.05, and p=0.02.
4. The receiver checks the received bits.
5. Repeat the above procedure many times (e.g., 100000 or more).
Pre-Lab Learning Material:
CRC or Cyclic Redundancy Check is a method of detecting accidental changes/errors in communication
channel.

Sender Side (Generation of Encoded Data from Data and Generator Polynomial (or Key)):

 The binary data is first augmented by adding k-1 zeros in the end of the data.
 Use modulo-2 binary division to divide binary data by the key and store remainder of division.
 Append the remainder at the end of the data to form the encoded data and send the same.
Receiver Side (Check if there are errors introduced in transmission)
 Perform modulo-2 division again and if remainder is 0, then there are no errors.
Modulo 2 Divisions:

The process of modulo-2 binary division is the same as the familiar division process we use for decimal numbers.
Just that instead of subtraction, we use XOR here.

 In each step, a copy of the divisor (or data) is XORed with the k bits of the dividend (or key).
 The result of the XOR operation (remainder) is (n-1) bits, which is used for the next step after 1 extra bit is
pulled down to make it n bits long.
 When there are no bits left to pull down, we have a result. The (n-1)-bit remainder which is appended at
the sender side.
Illustration:

Data word to be sent – 100100


Key - 1101 [ Or generator polynomial x3 + x2 + 1]

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


82

Sender Side:

Therefore, the remainder is 001 and hence the encoded


data sent is 100100001.
Receiver Side:
Code word received at the receiver side 100100001

Therefore, the remainder is all zeros. Hence, the


data received has no error.
Lab Learning Material II Year/V Sem CS8581-Networks Laboratory
83

Pre-Lab Questions:

1. How do you fix cyclic redundancy check?


2. What is cyclic redundancy check with example?

3. How do I fix cyclic redundancy check on SD card?

4. What causes data error cyclic redundancy check?

5. Why is cyclic redundancy check important?

6. How do I run chkdsk on an external hard drive?

Sample Exercise:

To simuate the Cyclic Redundancy check using Java program .

Source Code:
import java.util.*;

class CRC {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int n;

// Accept the input


System.out.println("Enter the size of the data:");
n = scan.nextInt();
int data[] = new int[n];
System.out.println("Enter the data, bit by bit:");
for(int i=0 ; i < n ; i++) {
System.out.println("Enter bit number " + (n-i) + ":");
data[i] = scan.nextInt();
}

// Accept the divisor


System.out.println("Enter the size of the divisor:");
n = scan.nextInt();
int divisor[] = new int[n];
System.out.println("Enter the divisor, bit by bit:");
for(int i=0 ; i < n ; i++) {
System.out.println("Enter bit number " + (n-i) + ":");
divisor[i] = scan.nextInt();
}

// Divide the inputted data by the inputted divisor

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


84

// Store the remainder that is returned by the method


int remainder[] = divide(data, divisor);
for(int i=0 ; i < remainder.length-1 ; i++) {
System.out.print(remainder[i]);
}
System.out.println("\nThe CRC code generated is:");

for(int i=0 ; i < data.length ; i++) {


System.out.print(data[i]);
}
for(int i=0 ; i < remainder.length-1 ; i++) {
System.out.print(remainder[i]);
}
System.out.println();

// Create a new array


// It will have the remainder generated by the above method appended
// to the inputted data
int sent_data[] = new int[data.length + remainder.length - 1];
System.out.println("Enter the data to be sent:");
for(int i=0 ; i < sent_data.length ; i++) {
System.out.println("Enter bit number " + (sent_data.length-i)
+ ":");
sent_data[i] = scan.nextInt();
}
receive(sent_data, divisor);
}

static int[] divide(int old_data[], int divisor[]) {


int remainder[] , i;
int data[] = new int[old_data.length + divisor.length];
System.arraycopy(old_data, 0, data, 0, old_data.length);
// Remainder array stores the remainder
remainder = new int[divisor.length];
// Initially, remainder's bits will be set to the data bits
System.arraycopy(data, 0, remainder, 0, divisor.length);

// Loop runs for same number of times as number of bits of data


// This loop will continuously exor the bits of the remainder and
// divisor
for(i=0 ; i < old_data.length ; i++) {
System.out.println((i+1) + ".) First data bit is : "
+ remainder[0]);
System.out.print("Remainder : ");
if(remainder[0] == 1) {
// We have to exor the remainder bits with divisor bits
for(int j=1 ; j < divisor.length ; j++) {
remainder[j-1] = exor(remainder[j], divisor[j]);
System.out.print(remainder[j-1]);
Lab Learning Material II Year/V Sem CS8581-Networks Laboratory
85

}
}
else {
// We have to exor the remainder bits with 0
for(int j=1 ; j < divisor.length ; j++) {
remainder[j-1] = exor(remainder[j], 0);
System.out.print(remainder[j-1]);
}
}
// The last bit of the remainder will be taken from the data
// This is the 'carry' taken from the dividend after every step
// of division
remainder[divisor.length-1] = data[i+divisor.length];
System.out.println(remainder[divisor.length-1]);
}
return remainder;
}

static int exor(int a, int b) {


// This simple function returns the exor of two bits
if(a == b) {
return 0;
}
return 1;
}

static void receive(int data[], int divisor[]) {


// This is the receiver method
// It accepts the data and divisor (although the receiver already has
// the divisor value stored, with no need for the sender to resend it)
int remainder[] = divide(data, divisor);
// Division is done
for(int i=0 ; i < remainder.length ; i++) {
if(remainder[i] != 0) {
// If remainder is not zero then there is an error
System.out.println("There is an error in received data...");
return;
}
}
//Otherwise there is no error in the received data
System.out.println("Data was received without any error.");
}
}

OUTPUT:

Output:
Enter the size of the data:
7
Lab Learning Material II Year/V Sem CS8581-Networks Laboratory
86

Enter the data, bit by bit:


Enter bit number 7:
1
Enter bit number 6:
0
Enter bit number 5:
0
Enter bit number 4:
1
Enter bit number 3:
1
Enter bit number 2:
0
Enter bit number 1:
1
Enter the size of the divisor:
4
Enter the divisor, bit by bit:
Enter bit number 4:
1
Enter bit number 3:
0
Enter bit number 2:
1
Enter bit number 1:
1
1.) First data bit is : 1
Remainder : 0101
2.) First data bit is : 0
Remainder : 1010
3.) First data bit is : 1
Remainder : 0011
4.) First data bit is : 0
Remainder : 0110
5.) First data bit is : 0
Remainder : 1100
6.) First data bit is : 1
Remainder : 1110
7.) First data bit is : 1
Remainder : 1010
101
The CRC code generated is:
1001101101
Enter the data to be sent:
Enter bit number 10:
1
Enter bit number 9:
0
Enter bit number 8:
Lab Learning Material II Year/V Sem CS8581-Networks Laboratory
87

0
Enter bit number 7:
1
Enter bit number 6:
1
Enter bit number 5:
0
Enter bit number 4:
1
Enter bit number 3:
1
Enter bit number 2:
0
Enter bit number 1:
1
1.) First data bit is : 1
Remainder : 0101
2.) First data bit is : 0
Remainder : 1010
3.) First data bit is : 1
Remainder : 0011
4.) First data bit is : 0
Remainder : 0111
5.) First data bit is : 0
Remainder : 1110
6.) First data bit is : 1
Remainder : 1011
7.) First data bit is : 1
Remainder : 0000
8.) First data bit is : 0
Remainder : 0000
9.) First data bit is : 0
Remainder : 0000
10.) First data bit is : 0
Remainder : 0000
Data was received without any error.

Student Exercise:
Calculate the CRC for the no 1010101 and 1101.

Viva Questions:

1. Can cyclic redundancy check errors be fixed?

2. How do I run chkdsk on uninitialized disk?

3. What do CRC errors indicate?

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


88

4. How do I fix Diskpart has encountered an error data error cyclic redundancy check?

5. What is cyclic redundancy check in computer networks?

6. How convert RAW to NTFS without formatting?

7. How many errors can CRC detect?

8. What is binary cyclic code?

9. How many errors can Hamming code detect?

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


89

Ex No: 11 MULTICASTING ROUTING PROTOCOL

Procedure:
1: start the program.
2: declare the global variables ns for creating a new simulator.
3: set the color for packets.
4: open the network animator file in the name of file2 in the write mode.
5: open the trace file in the name of file 1 in the write mode.
6: set the multicast routing protocol to transfer the packets in network.
7: create the multicast capable no of nodes.
8: create the duplex-link between the nodes including the delay time,bandwidth and dropping
. queue mechanism.
9: give the position for the links between the nodes.
10: set a udp connection for source node.
11: set the destination node ,port and random false for the source and destination files.
12: setup a traffic generator CBR for the source and destination files.
13: down the connection between any nodes at a particular time.
14: create the receive agent for joining and leaving if the nodes in the group.
15: define the finish procedure.
16: in the definition of the finish procedure declare the global variables.
17: close the trace file and namefile and execute the network animation file.
18: at the particular time call the finish procedure.
19: stop the program.

Pre Lab Learning Material:


Multicast is the capability to transmit the same information to multiple end users without being forced to
address the latter singly and without having, hence, the need to duplicate for each of them the information to
spread.

Multicast routing is in charge of deciding and propagating information needed to forward multicast
packets outside Local Area Networks among multiple interconnected multicast routers (mrouter) over the
network:

 determining the existence of receivers on a particular LAN segment: in case no receivers exist, it
does not make sense to forward those packets to the LAN → the networks which have no
receivers are cut away from the tree (pruning);
 propagating the existence and location of receivers over the whole IP network: multicast routing
should keep track of locations of the various receivers, creating a 'spanning tree', called
distribution tree, so as to minimize costs and deliver packets to everyone;
 transmitting and forwarding data: transmitters generate packets with a particular multicast
destination address, and mrouters forward them along the distribution tree up to receivers.

Multicast routing algorithms use two types of distribution tree:

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


90

source-specific tree (RPB, TRPB, RPM, Link State): there is one tree for every sender → paths are optimal, but
updates are more complex;
shared tree (CBT): there is one tree for every multicast group, valid for all senders → updates are simpler, but
paths are not optimal.
Prelab Questions:

1. Which protocol is used for multicasting?

2. What is Multicast routing?

3. What are the different kinds of multicast routing?

4. What is Unicast and Multicast routing protocols?

5. What is the difference between multicasting and broadcasting?

6. Is multicast TCP or UDP?

Sample Program:

# Create scheduler
#Create an event scheduler wit multicast turned on
set ns [new Simulator -multicast on]
#$ns multicast
#Turn on Tracing
set tf [open output.tr w]
$ns trace-all $tf
# Turn on nam Tracing
set fd [open mcast.nam w]
$ns namtrace-all $fd
# Create nodes
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]
# Create links
$ns duplex-link $n0 $n2 1.5Mb 10ms DropTail
$ns duplex-link $n1 $n2 1.5Mb 10ms DropTail
$ns duplex-link $n2 $n3 1.5Mb 10ms DropTail
$ns duplex-link $n3 $n4 1.5Mb 10ms DropTail
$ns duplex-link $n3 $n7 1.5Mb 10ms DropTail
$ns duplex-link $n4 $n5 1.5Mb 10ms DropTail
$ns duplex-link $n4 $n6 1.5Mb 10ms DropTail

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


91

# Routing protocol: say distance vector


#Protocols: CtrMcast, DM, ST, BST
set mproto DM
set mrthandle [$ns mrtproto $mproto {}]
# Allocate group addresses
set group1 [Node allocaddr]
set group2 [Node allocaddr]
# UDP Transport agent for the traffic source
set udp0 [new Agent/UDP]
$ns attach-agent $n0 $udp0
$udp0 set dst_addr_ $group1
$udp0 set dst_port_ 0
set cbr1 [new Application/Traffic/CBR]
$cbr1 attach-agent $udp0
# Transport agent for the traffic source
set udp1 [new Agent/UDP]
$ns attach-agent $n1 $udp1
$udp1 set dst_addr_ $group2
$udp1 set dst_port_ 0
set cbr2 [new Application/Traffic/CBR]
$cbr2 attach-agent $udp1
# Create receiver
set rcvr1 [new Agent/Null]
$ns attach-agent $n5 $rcvr1
$ns at 1.0 "$n5 join-group $rcvr1 $group1"
set rcvr2 [new Agent/Null]
$ns attach-agent $n6 $rcvr2
$ns at 1.5 "$n6 join-group $rcvr2 $group1"
set rcvr3 [new Agent/Null]
$ns attach-agent $n7 $rcvr3
$ns at 2.0 "$n7 join-group $rcvr3 $group1"
set rcvr4 [new Agent/Null]
$ns attach-agent $n5 $rcvr1
$ns at 2.5 "$n5 join-group $rcvr4 $group2"
set rcvr5 [new Agent/Null]
$ns attach-agent $n6 $rcvr2
$ns at 3.0 "$n6 join-group $rcvr5 $group2"
set rcvr6 [new Agent/Null]
$ns attach-agent $n7 $rcvr3
$ns at 3.5 "$n7 join-group $rcvr6 $group2"
$ns at 4.0 "$n5 leave-group $rcvr1 $group1"
$ns at 4.5 "$n6 leave-group $rcvr2 $group1"
$ns at 5.0 "$n7 leave-group $rcvr3 $group1"
$ns at 5.5 "$n5 leave-group $rcvr4 $group2"
$ns at 6.0 "$n6 leave-group $rcvr5 $group2"
$ns at 6.5 "$n7 leave-group $rcvr6 $group2"
# Schedule events
$ns at 0.5 "$cbr1 start"
$ns at 9.5 "$cbr1 stop"
Lab Learning Material II Year/V Sem CS8581-Networks Laboratory
92

$ns at 0.5 "$cbr2 start"


$ns at 9.5 "$cbr2 stop"
#post-processing
$ns at 10.0 "finish"
proc finish {} {
global ns tf
$ns flush-trace
close $tf
exec nam mcast.nam &
exit 0
}

# For nam
#Colors for packets from two mcast groups
$ns color 10 red
$ns color 11 green
$ns color 30 purple
$ns color 31 green
# Manual layout: order of the link is significant!
#$ns duplex-link-op $n0 $n1 orient right
#$ns duplex-link-op $n0 $n2 orient right-up
#$ns duplex-link-op $n0 $n3 orient right-down
# Show queue on simplex link n0->n1
#$ns duplex-link-op $n2 $n3 queuePos 0.5
# Group 0 source
$udp0 set fid_ 10
$n0 color red
$n0 label "Source 1"
# Group 1 source
$udp1 set fid_ 11
$n1 color green
$n1 label "Source 2"
$n5 label "Receiver 1"
$n5 color blue
$n6 label "Receiver 2"
$n6 color blue
$n7 label "Receiver 3"
$n7 color blue
#$n2 add-mark m0 red
#$n2 delete-mark m0"
# Animation rate
$ns set-animation-rate 3.0ms
$ns run

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory


93

Viva Questions:

1. How does Multicast routing work?


2. Can multicast be TCP?

3. Which addresses are reserved for multicasting?


4. Does multicast work over the Internet?
5. Does Youtube use multicast?
6. Are multicast addresses routable?
7. Which multicast address does the OSPF Hello protocol use?
8. What are addresses in the 224.0 0.0 range used for?
9. Does OSPF use multicast?
10. How does OSPF choose DR and BDR?

Lab Learning Material II Year/V Sem CS8581-Networks Laboratory

Das könnte Ihnen auch gefallen