Beruflich Dokumente
Kultur Dokumente
(Regulation 2017)
Prepared By
Dr.K.Vishnukumar ASP/CSE
TABLE OF CONTENTS
File Transfer
Syllabus
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
LAB PLAN
10
11
Procedure:
Execute commands in command prompt and look for the output.
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
Fedora
Ubuntu/Debian/Linux Mint
On Ubuntu or Debian or Linux Mint, install tcp dumo using the following command,
For windows
You will need to place your network card into promiscuous mode – for this, install WinPcap.
Change the directory to your download directory – normally in windows this is:
cd c:\Users\Smile\Downloads
You may have several adapters listed. You select the interface to start running windump (as shown in step 5
using interface number 2).
windump -i 2 -q -w C:\perflogs\diagTraces -n -C 30 -W 10 -U -s 0
Wireshark will reveal all the packet data. Double click on each event, to drill down to more data.
Or click on the “Protocol” Column, to sort by Arp, TCP, UDP or DNS etc.
ii. Netstat
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.
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.
ipconfig /renew - Renew the IP address of network adapter, mainly used for network adapter that relies on DHCP
server to obtain IP address.
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.
nslookup www.google.com
at a command prompt.
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.
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.
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.
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
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.
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:
EX No 2 Write a HTTP web client program to download a web page using TCP sockets
Procedure:
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.
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:
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.
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 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).
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.
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:
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.
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
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.
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?
Procedure:
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 5: After the Successful connection Client & Server Applications can send &
receive messages.
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
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.
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.
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.
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:
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
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.
}
}
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.
Client.java
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.
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.
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();
}
}
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.
Sample programs:
EchoServer.java
import java.io.*;
import java.net.*;
Echo.Client.java
import java.io.*;
import java.net.*;
import java.net.*;
import java.io.*;
public class Server {
os.write(bytearray,0,bytearray.length);
os.flush();
socket.close();
System.out.println("File transfer complete");
}
}
import java.net.*;
import java.io.*;
public class Client {
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:
EchoServer
:/>javac EchoServer.java
:/>java EchoServer
EchoClient
:/>javac EchoClient.java
:/>java EchoClient
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:
Procedure:
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).
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.
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.
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.
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.
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.
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.
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.
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
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:
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.
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.
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.
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.
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.
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:
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:
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)
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.
setSoTimeout(int timeout): sets timeout in milliseconds, limiting the waiting time when receiving data. If
the timeout expires, a SocketTimeoutException is raised.
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
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
Output:
Student Exercise:
1. Write a java code to display the domain name when an ip address is given and vice versa?
Viva Questions:
Procedure:
Client
Server
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
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.
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).
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.*;
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();
}
String line;
}
if((line == null))
System.out.println("Not found");
fr.close();
br.close();
}
String line;
if((line == null))
System.out.println("Not found");
fr.close();
br.close();
}
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
Student Exercise:
1. Write a java program to display physical address for the given logical address.
Viva Questions:
Procedure
1. Download and Extract ns2.
2. Building the dependencies.
3. Install ns2 using this code
sudo su cd ~/ns-allinone-2.35/./install
6. Running ns2
Ns
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
NS Simulator Preliminaries.
In order to have output files with data on the simulation (trace files) or files used for visualization (nam
files), we need to create the files using ―open command:
The 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
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.
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:
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.
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.
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:
Procedure
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
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
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
UDP performance
TCP performance
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
TCP Performance
Prelab Questions
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?
Procedure:
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,
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:
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.
1. What are the three main elements of distance vector routing algorithm?
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
}
$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 45 "finish"
$ns run
OUTPUT:
Student Exercise:
1. Simulate and study the Link State routing algorithm using simulation.
Viva Questions:
8. Can increasing the routing cost of a link cause the count to infinity problem?
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.
5. In the destination node AODV::recv(Packet*p, Handler*) is called, but actually this is done after the
node is receiving a packet.
7. Hence, the flow goes to the AODV::recvAODV(Packet *p) function, which will check different packets
types and call the respective function.
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:
Source Code:
#ANNOTATIONS DETAILS
proc stop {} {
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:
Procedure:
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:
Sender Side:
Pre-Lab Questions:
Sample Exercise:
Source Code:
import java.util.*;
class CRC {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int n;
}
}
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;
}
OUTPUT:
Output:
Enter the size of the data:
7
Lab Learning Material II Year/V Sem CS8581-Networks Laboratory
86
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:
4. How do I fix Diskpart has encountered an error data error cyclic redundancy check?
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.
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.
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:
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
# 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
Viva Questions: