CS8581-Networks Lab - Manual PDF
CS8581-Networks Lab - Manual PDF
CS8581-Networks Lab - Manual PDF
BATCH OF 30 STUDENTS:
HARDWARE:
1. Standalone desktops 30 Nos
SOFTWARE:
2. C / C++ / Java / Python / Equivalent Compiler 30
3. Network simulator like NS2/Glomosim/OPNET/ Packet Tracer / Equivalent
Exp #1 Network Utitilities
Date:
1. ping
Verifies IP-level connectivity to another TCP/IP computer by sending Internet Control
Message Protocol (ICMP) Echo Request messages. The receipt of corresponding Echo Reply
messages are displayed, along with round-trip times. Ping is the primary TCP/IP command
used to troubleshoot connectivity, reachability, and name resolution.
To test a TCP/IP configuration, ping the loopback address by typing ping 127.0.0.1
The results should tell if the connection was successful or if there is any lost packets due to
poor network connection or congestion.
2. ifconfig / ipconfig
Displays basic current TCP/IP network configuration. It is very useful to troubleshoot
networking problems. ipconfig/all is used to provide detailed information such as IP
address, subnet mask, MAC address, DNS server, DHCP server, default gateway etc.
ipconfig/renew is used to renew a DHCP assigned IP address whereas
ipconfig/release is used to discard the assigned DHCP IP address.
3. traceroutet / tracert
Displays the path taken to a destination by sending ICMP Echo Request messages to the
destination with TTL field values. The path displayed is the list of nearest router interfaces
taken along each hop in the path between source host and destination.
1
4. netstat
Displays active TCP connections, ports on which the computer is listening, Ethernet
statistics, IP routing table, IPv4 statistics and IPv6 statistics. It indicates state of a TCP
connection. it's a helpful tool in finding problems and determining the amount of traffic on
the network as a performance measurement.
5. nslookup
It provides a command-line utility for querying DNS table of a DNS Server. It returns IP
address for the given host name.
2
6. tcpdump
tcpdump is a most powerful and widely used command-line packets sniffer or package
analyzer tool which is used to capture or filter TCP/IP packets that received or transferred
over a network on a specific interface for analysis.
Result
Thus TCP/IP network command utilities were executed.
3
Exp# 1a Ping Command
Date:
Aim
To test the communication between hosts at IP level using Ping command.
Algorithm
1. Get IP address / domain name from the user.
2. Create a runtime environment.
3. Execute ping command with given input as parameter.
4. Analyse the output
5. Stop
4
Program
import java.io.*;
import java.net.*;
class PingServer
{
public static void main(String args[])
{
try
{
String str;
System.out.print("Enter IP address/domain name: ");
BufferedReader buf1=new BufferedReader(new
InputStreamReader(System.in));
String ip = buf1.readLine();
Runtime rt = Runtime.getRuntime();
Process p = rt.exec("ping " + ip);
InputStream in = p.getInputStream();
BufferedReader buf2 = new BufferedReader(new
InputStreamReader(in));
while((str=buf2.readLine()) != null)
{
System.out.println(" " + str);
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
5
Output
$ javac PingServer.java
$ java PingServer
Enter IP address/domain name: gmail.com
^C
Result
Thus using Ping command, connective and communicative status is determined.
6
Exp# 1b Traceroute Command
Date:
Aim
To trace the path traversed by a packet from host to destination using Traceroute
command.
Algorithm
1. Get domain name from the user.
2. Create a runtime environment.
3. Execute traceroute command with given input as parameter.
4. Analyse the output
5. Stop
7
Program
import java.io.*;
import java.net.*;
class TraceServer
{
public static void main(String args[])
{
try
{
String str;
System.out.print("Enter domain name : ");
BufferedReader buf1=new BufferedReader(new
InputStreamReader(System.in));
String ip = buf1.readLine();
Runtime rt = Runtime.getRuntime();
Process p = rt.exec("tracert " + ip);
InputStream in = p.getInputStream();
BufferedReader buf2 = new BufferedReader(new
InputStreamReader(in));
while((str=buf2.readLine()) != null)
{
System.out.println(" " + str);
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
8
Output
$ javac TraceServer.java
$ java TraceServer
Enter domain name: yahoo.com
Trace complete.
Result
Thus using traceroute command, path traversed by the packet is determined.
9
Exp# 2 WebPage Download
Date:
Aim
To download a web page using java URL method.
Algorithm
1. Get URL from the user.
2. Create a file instance to store the downloaded page.
3. Download the page using java URL methods.
4. View the download page
5. Stop
10
Program
import java.io.*;
import java.net.*;
class MyDownload
{
public void Download() throws Exception
{
try
{
String WebPage, MyPage;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
// URL Instance
System.out.print("Enter the URL : ");
WebPage = br.readLine();
URL url = new URL(WebPage);
// File Instance
System.out.print("Enter filename to store : ");
MyPage = br.readLine();
File Out = new File(MyPage);
FileOutputStream FOS = new FileOutputStream(Out);
}
catch (MalformedURLException M)
{
System.out.println(M);
}
11
catch (Exception E)
{
System.out.println(E);
}
}
}
class DownloadPage
{
public static void main(String args[]) throws Exception
{
String Choice;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
MyDownload MDP = new MyDownload();
MDP.Download();
System.out.println("Download complete. View the file");
}
}
12
Output
$ javac DownloadPage.java
$ java DownloadPage
Enter the URL : http://www.google.co.in
Enter filename to store : mypage.html
Download complete. View the file
Result
Thus using java URL methods, a webpage is downloaded.
13
TCP Sockets
To communicate over TCP, a client program and a server program establish a connection to
one another. Each program binds a socket to its end of the connection. A server runs on a
specific computer and has a socket that is bound to a specific port number. The server waits,
listening to the socket for a connection request from the client.
On the client-side, the client knows the hostname of the machine on which the server is
running and the port number on which the server is listening. To make a connection request,
the client tries to make contact with the server on the server's machine and port. The client
also needs to identify itself to the server so it binds to a local port number that it will use
during this connection.
If everything goes well, the server accepts the connection. Upon acceptance, the server gets a
new socket bound to the same local port and also has its remote endpoint set to the address
and port of the client. It needs a new socket so that it can continue to listen to the original
socket for connection requests while tending to the needs of the connected client.
On the client side, if the connection is accepted, a socket is successfully created and the client
can use the socket to communicate with the server. The client and server can now
communicate by writing to or reading through I/O streams from their sockets and eventually
close it.
The two key classes from the java.net package used in creation of server and client programs
are:
ServerSocket
Socket
14
Exp# 3a TCP Echo Server/Client
Date:
Aim
To implement echo server and client in java using TCP sockets.
Algorithm
Server
1. Create a server socket.
2. Wait for client to be connected.
3. Read text from the client
4. Echo the text back to the client.
5. Repeat steps 4-5 until ‘bye’ or ‘null’ is read.
6. Close the I/O streams
7. Close the server socket
8. Stop
Client
1. Create a socket and establish connection with the server
2. Get input from user.
3. If equal to bye or null, then go to step 7.
4. Send text to the server.
5. Display the text echoed by the server
6. Repeat steps 2-4
7. Close the I/O streams
8. Close the client socket
9. Stop
15
Program
import java.net.*;
import java.io.*;
16
//TCP Echo Client--tcpechoclient.java
import java.net.*;
import java.io.*;
17
}
}
Output
Server Console
$ javac tcpechoserver.java
$ java tcpechoserver
Server Ready
Client Connected
Client [ hello ]
Client [ how are you ]
Client [ i am fine ]
Client [ ok ]
Client Disconnected
Client Console
$ javac tcpechoclient.java
$ java tcpechoclient
Type "bye" to quit
Enter msg to server : hello
Server [ hello ]
Enter msg to server : how are you
Server [ how are you ]
Enter msg to server : i am fine
Server [ i am fine ]
Enter msg to server : ok
Server [ ok ]
Enter msg to server : bye
Result
Thus data from client to server is echoed back to the client to check reliability/noise level
of the channel.
18
Exp# 3b TCP Chat Server/Client
Date:
Aim
To implement a chat server and client in java using TCP sockets.
Algorithm
Server
1. Create a server socket
2. Wait for client to be connected.
3. Read Client's message and display it
4. Get a message from user and send it to client
5. Repeat steps 3-4 until the client sends "end"
6. Close all streams
7. Close the server and client socket
8. Stop
Client
1. Create a client socket and establish connection with the server
2. Get a message from user and send it to server
3. Read server's response and display it
4. Repeat steps 2-3 until chat is terminated with "end" message
5. Close all input/output streams
6. Close the client socket
7. Stop
19
Program
// TCP Chat Server--tcpchatserver.java
import java.io.*;
import java.net.*;
class tcpchatserver
{
public static void main(String args[])throws Exception
{
PrintWriter toClient;
BufferedReader fromUser, fromClient;
try
{
ServerSocket Srv = new ServerSocket(5555);
System.out.print("\nServer started\n");
Socket Clt = Srv.accept();
System.out.println("Client connected");
toClient = new PrintWriter(new BufferedWriter(new
OutputStreamWriter(Clt.getOutputStream())), true);
fromClient = new BufferedReader(new
InputStreamReader(Clt.getInputStream()));
fromUser = new BufferedReader(new
InputStreamReader(System.in));
String CltMsg, SrvMsg;
while(true)
{
CltMsg= fromClient.readLine();
if(CltMsg.equals("end"))
break;
else
{
System.out.println("\nServer <<< " +
CltMsg);
System.out.print("Message to Client : ");
SrvMsg = fromUser.readLine();
toClient.println(SrvMsg);
}
}
System.out.println("\nClient Disconnected");
fromClient.close();
toClient.close();
fromUser.close();
Clt.close();
Srv.close();
}
catch (Exception E)
{
System.out.println(E.getMessage());
}
}
}
20
// TCP Chat Client--tcpchatclient.java
import java.io.*;
import java.net.*;
class tcpchatclient
{
public static void main(String args[])throws Exception
{
Socket Clt;
PrintWriter toServer;
BufferedReader fromUser, fromServer;
try
{
if (args.length > 1)
{
System.out.println("Usage: java hostipaddr");
System.exit(-1);
}
if (args.length == 0)
Clt = new Socket(InetAddress.getLocalHost(),5555);
else
Clt = new Socket(InetAddress.getByName(args[0]),
5555);
toServer = new PrintWriter(new BufferedWriter(new
OutputStreamWriter(Clt.getOutputStream())), true);
fromServer = new BufferedReader(new
InputStreamReader(Clt.getInputStream()));
fromUser = new BufferedReader(new
InputStreamReader(System.in));
String CltMsg, SrvMsg;
System.out.println("Type \"end\" to Quit");
while (true)
{
System.out.print("\nMessage to Server : ");
CltMsg = fromUser.readLine();
toServer.println(CltMsg);
if (CltMsg.equals("end"))
break;
SrvMsg = fromServer.readLine();
System.out.println("Client <<< " + SrvMsg);
}
}
catch(Exception E)
{
System.out.println(E.getMessage());
}
}
}
21
Output
Server Console
$ javac tcpchatserver.java
$ java tcpchatserver
Server started
Client connected
Server <<< hi
Message to Client : hello
Client Disconnected
Client Console
$ javac tcpchatclient.java
$ java tcpchatclient
Type "end" to Quit
Message to Server : hi
Client <<< hello
Result
Thus both the client and server exchange data using TCP socket programming.
22
Exp# 3c TCP File Server/Client
Date:
Aim
To implement a file server and client in java using TCP sockets.
Algorithm
Server
1. Create a server socket
2. Wait for client to be connected.
3. Read filename from client
4. Open the file using java File methods
5. Write file contents onto stream until EOF
6. Close all streams
7. Close the server and client socket
8. Stop
Client
1. Create a client socket and establish connection with the server
2. Get filename from user and send it to server
3. Read file contents from server stream and display it
4. Close all input/output streams
5. Close the client socket
6. Stop
23
Program
// TCP File Server -- FileServer.java
import java.io.*;
import java.net.*;
if(args.length == 0)
dir = new File("./");
else
dir = new File(args[0]);
if(!dir.exists() || !dir.isDirectory())
{
System.out.println("Directory does not exist");
System.exit(-1);
}
try
{
ss = new ServerSocket(3210);
conn = ss.accept();
br = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
pw = new PrintWriter(conn.getOutputStream());
24
System.out.println("File Transferred\n");
}
pw.flush();
pw.close();
}
catch(Exception e) {
System.out.println("Error: " + e);
}
}
}
System.out.print("\nFilename : ");
CltMsg = br.readLine();
OS.println(CltMsg);
Server Console
$ javac FileServer.java
$ java FileServer
File Transferred
Client Console
$ javac FileClient.java
$ java FileClient
Filename : hello.java
import java.io.*;
class hello
{
public static void main(String args[])
{
System.out.println("hello");
}
}
Result
Thus file contents was sent from server to client using TCP socket programming.
26
UDP Sockets
TCP guarantees the delivery of packets and preserves their order on destination. Sometimes
these features are not required, since they do not come without performance costs, it would
be better to use a lighter transport protocol such as UDP (User Datagram Protocol). UDP is
an unreliable protocol, i.e., it does not include software mechanisms for retrying on
transmission failures or data corruption (unlike TCP), and has restrictions on message length
(< 65536 bytes). Examples are NFS, DNS, SNMP, Clock Server, Ping, VoIP, online games
etc.
Unlike TCP there is no concept of a connection, UDP is a protocol that sends independent
packets of data, called datagrams, from one computer to another with no guarantees
about arrival and sequencing. No packet has any knowledge of the preceding or following
packet. The recipient does not acknowledge packets, thereby the sender does not know
whether the transmission was successful. The format of datagram packet is
A program can use a single UDP socket to communicate with more than one host and port
number, but it is convenient for most UDP client programs to maintain the fiction that there is
a connection, by keeping a local record of each server host and port number. A UDP server
does not have to listen for and accept client connections, and a UDP client need not connect
to a server.
The DatagramPacket object is the data container, while the DatagramSocket is the
mechanism used to send or receive the DatagramPackets.
27
Exp# 4 UDP DNS Server/Client
Date:
Aim
To implement a DNS server and client in java using UDP sockets.
Algorithm
Server
1. Define a array of hosts and its corresponding IP address in another array
2. Create a datagram socket
3. Create a datagram packet to receive client request
4. Read the domain name from client to be resolved
5. Lookup the host array for the domain name
6. If found then retrieve corresponding address
7. Construct a datagram packet to send response back to the client
8. Repeat steps 3-7 to resolve further requests from clients
9. Close the server socket
10. Stop
Client
1. Create a datagram socket
2. Get domain name from user
3. Construct a datagram packet to send domain name to the server
4. Create a datagram packet to receive server message
5. If it contains IP address then display it, else display "Domain does not exist"
6. Close the client socket
7. Stop
28
Program
import java.io.*;
import java.net.*;
while (true)
{
DatagramSocket serversocket=new DatagramSocket(1362);
byte[] senddata = new byte[1021];
byte[] receivedata = new byte[1021];
29
serversocket.close();
}
}
}
import java.io.*;
import java.net.*;
30
Output
Server Console
$ javac udpdnsserver.java
$ java udpdnsserver
Press Ctrl + C to Quit
Request for host yahoo.com
Client Console
$ javac udpdnsclient.java
$ java udpdnsclient
Enter the hostname : yahoo.com
IP Address: 68.180.206.184
Result
Thus domain name requests by the client are resolved into their respective logical
address using lookup method.
31
Address Resolution
A host or router to send an IP datagram, needs to know both the logical and physical
address of the destination.
32
Exp# 5a ARP Client/Server
Date:
Aim
To know the physical address of a host when its logical address is known using ARP
protocol.
Algorithm
Target/Server
1. Create a server socket.
2. Accept client connection.
3. Read IP address from the client request
4. Check its configuration file and compare with its logical address.
5. If there is a match, send the host physical address.
6. Stop
Client
1. Create a socket.
2. Send IP address to the target machine
3. Receive target's response
4. If it is a MAC address then display it and go to step 6
5. Display "Host not found"
6. Stop
33
Program
class arpserver
{
public static void main(String args[])throws IOException
{
try
{
ServerSocket soc = new ServerSocket(2500);
System.out.println("Server started");
Socket client = null;
client = soc.accept();
String str;
PrintStream ps = new
PrintStream(client.getOutputStream());
BufferedReader br = new BufferedReader(new
InputStreamReader(client.getInputStream()));
Runtime r = Runtime.getRuntime();
Process p = r.exec("ifconfig eth0");
BufferedReader pin=new BufferedReader(new
InputStreamReader(p.getInputStream()));
String haddr = "";
String ipaddr = br.readLine();
int flag = 0;
while((str = pin.readLine())!=null)
{
System.out.println(str);
if((str.indexOf("HWaddr")) != -1)
{
int tlen = str.length();
int hlen = tlen - 19;
haddr = str.substring(hlen,tlen);
}
else if ((str.indexOf(ipaddr)) != -1)
{
flag = 1;
}
}
if (flag == 1)
ps.println(haddr);
ps.close();
br.close();
pin.close();
client.close();
34
soc.close();
}
catch(IOException io)
{
System.err.println("Exception : " + io.toString());
}
}
}
class arpclient
{
public static void main(String args[])
{
try
{
Socket client = new Socket("localhost", 2500);
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
PrintStream ps = new
PrintStream(client.getOutputStream());
String ipaddr,haddr = null;
BufferedReader sin = new BufferedReader(new
InputStreamReader(client.getInputStream()));
35
Output
Server
$ javac arpserver.java
$ java arpserver
Server started
eth0 Link encap:Ethernet HWaddr B8:AC:6F:1B:AB:06
inet addr:172.16.12.251 Bcast:172.255.255.255 Mask:255.0.0.0
inet6 addr: fe80::baac:6fff:fe1b:ab06/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:450 errors:0 dropped:0 overruns:0 frame:0
TX packets:127 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:48118 (46.9 KiB) TX bytes:21025 (20.5 KiB)
Interrupt:16
Client
$ javac arpclient.java
$ java arpclient
Enter the IP address : 172.16.12.251
Physical Address B8:AC:6F:1B:AB:06
Result
Thus using ARP protocol, server’s MAC address is obtained.
36
Exp# 5b RARP Client/Server
Date:
Aim
To know the logical address of a host when its physical address is known using RARP
protocol.
Algorithm
Target/Server
1. Create a server socket.
2. Accept client connection.
3. Read MAC address from the client request
4. Check its configuration file and compare with its physical address.
5. If there is a match, send the host logical address.
6. Stop
Client
1. Create a socket.
2. Send physical address to the target machine
3. Receive target's response
4. If it is a IP address then display it and go to step 6
5. Display "Host not found"
6. Stop
37
Program
38
}
catch(IOException io)
{
System.err.println("Exception : " + io.toString());
}
}
}
class rarpclient
{
public static void main(String args[])
{
try
{
Socket client = new Socket("localhost", 2500);
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
PrintStream ps = new
PrintStream(client.getOutputStream());
String haddr,ipaddr = null;
BufferedReader sin = new BufferedReader(new
InputStreamReader(client.getInputStream()));
System.out.print("Enter the physical address : ");
haddr = br.readLine();
ps.println(haddr);
ipaddr = sin.readLine();
if (ipaddr == null)
System.out.println("Host does not exist");
else
System.out.println("Logical Address " + ipaddr);
ps.close();
br.close();
client.close();
}
catch(IOException io)
{
System.err.println(io.toString());
}
}
}
39
Output
Server
$ javac rarpserver.java
$ java rarpserver
Server started
eth0 Link encap:Ethernet HWaddr B8:AC:6F:1B:AB:06
inet addr:172.16.12.251 Bcast:172.255.255.255 Mask:255.0.0.0
inet6 addr: fe80::baac:6fff:fe1b:ab06/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:450 errors:0 dropped:0 overruns:0 frame:0
TX packets:127 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:48118 (46.9 KiB) TX bytes:21025 (20.5 KiB)
Interrupt:16
Client
$ javac rarpclient.java
$ java rarpclient
Enter the physical address : B8:AC:6F:1B:AB:06
Logical Address 172.16.12.251
Result
Thus using RARP protocol, IP address of the server is obtained.
40
Exp#6 NS2 SIMULATION
Date:
A simulator is a device, software or system which behaves or operates like a given system
when provided with a set of controlled inputs. The need for simulators is:
Provide users with practical feedback such as accuracy, efficiency, cost, etc., when
designing real world systems.
Permit system designers to study at several different levels of abstraction
Simulation can give results that are not experimentally measurable with our current
level of technology.
Simulations take the building/rebuilding phase out of the loop by using the model
already created in the design phase.
Effective means for teaching or demonstrating concepts to students.
A few popular network simulators are NS-2, OPNET, GLOMOSIM, etc.
Network Simulator NS2
NS2 is an object-oriented, discrete event driven network simulator developed at UC Berkley
written in C++ and OTcl (Object-oriented Tool Command Language). NS is useful for
simulating local and wide area networks. NS2 is an open-source simulation tool that
primarily runs on Linux (cygwin for Windows). The features of NS2 are:
Is a discrete event simulator for networking research
Works at packet level.
Provide support to simulate bunch of protocols like TCP, UDP, FTP, etc.
Simulate wired and wireless network.
Is a standard experiment environment in research community.
Class Hierarchy
41
Create Visualize
Terrestrial, satellite and wireless Packet flow, queue build-up and packet
network with various routing algorithm drops.
(DV, LS, PIM, DSR). Protocol behavior: TCP slow start, self-
Traffic sources like web, ftp, telnet, cbr, clocking, congestion control, fast
and stochastic traffic. retransmit and recovery.
Failures, including deterministic, Node movement in wireless networks.
probabilistic loss, link failure, etc. Annotations to highlight important
Various queuing disciplines (drop-tail, events.
RED, FQ, SFQ, etc.) and QoS Protocol state (e.g., TCP cwnd).
NS2 Execution
The overall simulation procedure in NS is shown below. NS is composed of OTcl Script and
Interpreter. NS simulation results can be observed through graphs by analyzing the trace file
or viewing animations with NAM.
$ ns filename.tcl
Event Scheduler
a Creating event scheduler
set ns [new Simulator]
b Schedule events
$ns at time "event"
c Start scheduler
$ns run
42
Creating Network
a Create set of Nodes
set n0 [$ns node]
set n1 [$ns node]
b Create links and queuing
$ns duplex-link $n0 $n1 bandwidth delay queue_type
Bandwidth is generally in MB
Delay is generally in ms
Queue type is either DropTail, RED, CBQ, FQ, SFQ, etc
$ns duplex-link $n0 $n2 1Mb 10ms DropTail
c Layout
$ns duplex-link-op $n0 $n2 orient position
where position is either right, right-up, right-down, left, left-
up, left-down, up, down
d Marking flows
$ns color 1 Blue
$ns color 2 Red
$udp0 set class_ 1
$udp1 set class_ 2
Tracing
a NAM Trace all links (must succeed scheduler creation)
set nf [open out.nam w]
$ns namtrace-all $nf
b Trace all links (must succeed scheduler creation)
set tf [open out.tr w]
$ns trace-all $tf
Trace file ouput format
event, time, from_node, to_node, pkt type, pkt size, flags, fid, src_addr, dst_addr,
seq_num, pkt_id
where events are r received, + enqueued, - dequeued, d dropped
c Tracing specific links
$ns trace-queue $n0 $n1
$ns namtrace-queue $n0 $n1
43
Connection
a UDP
set udp [new Agent/UDP]
set null [new Agent/Null]
$ns attach-agent $n0 $udp0
$ns attach-agent $n1 $null
$ns connect $udp0 $null
b TCP
set tcp0 [new Agent/TCP/FullTcp]
$tcp0 set window_ 30
$tcp0 set segsize_ 536
$ns attach-agent $n0 $tcp0
set sink0 [new Agent/TCP/FullTcp]
$ns attach-agent $n5 $sink0
$sink0 listen
$ns connect $tcp0 $sink0
Traffic Generation
a UDP
set src [new Application/Traffic/type]
$src attach-agent $udp0
where type is either CBR, Exponential, Pareto
b TCP
set ftp [new Application/FTP]
$ftp attach-agent $tcp
set telnet [new Application/Telnet]
$telnet attach-agent $tcp
Finish procedure
a Flush NS tracing, Close tracing files and execute any post-analysis programs (display
results, run NAM, etc)
proc finish {} {
global ns nf
$ns flush-trace
close $nf
exec nam out.nam &
exit 0
}
Result
Thus simulator NS2 and its basic commands was studied.
44
Exp# 7a Study of UDP Performance
Date:
Aim
To study the performance of UDP by simulating a simple network
Algorithm
1. Create a simulator object
2. Define different color for data flows
3. Trace all events in a nam file.
4. Create four nodes n0, n1, n2 and n3
5. Describe their layout topology
6. Specify the link capacity between nodes
7. Monitor queue on the link n2 to n3 vertically 90°
8. Create a UDP agents udp0, udp1 and attach it to nodes n0 and n1 respectively
9. Create a CBR traffic cbr0, cbr1 and attach it to udp0 and udp1 respectively
10. Create a traffic sink and attach it to node n3
11. Connect sources to the sink
12. Label the nodes
13. Schedule cbr0 to start at 0.5 and stop at 4.5 seconds
14. Schedule cbr1 to start at 1.0 and stop at 4.0 seconds
15. Call finish procedure at 5.0 seconds
16. Run the simulation
17. Execute NAM on the trace file
18. Observe simulated events on the NAM and packet flow on link n2 to n3
19. Stop
45
Program
46
# Create a CBR traffic source and attach it to udp1
set cbr1 [new Application/Traffic/CBR]
$cbr1 set packetSize_ 500
$cbr1 set interval_ 0.005
$cbr1 attach-agent $udp1
47
Output
$ ns UDP.tcl
Result
Thus the performance of UDP and basic network terminologies were studied using
NS2.
48
Exp# 7b Study of TCP Performance
Date:
Aim
To study the performance of a TCP network with droptail queue mechanism on the
gateway
Algorithm
1. Create a simulator object
2. Define different flows for data flows
3. Trace all events in a nam file and text file
4. Create source nodes (s1, s2, s3), gateway (G) and receiver (r)
5. Describe their layout topology
6. Specify the link between nodes
7. Define the queue size between nodes G and r as 5
8. Monitor queue on all links vertically 90°
9. Create TCP agents tcp1, tcp2, tcp3 and attach it to nodes s1, s2 and s3 respectively
10. Create three TCP sinks and attach it to node r
11. Connect traffic sources to the sink
12. Create FTP agents ftp1, ftp2, ftp3 and attach it to tcp1, tcp2 and tcp3 respectively
13. Label the nodes at start time
14. Schedule ftp1, ftp2, ftp3 to start at 0.1 and stop at 5.0 seconds
15. Call finish procedure at 5.25 seconds
16. Run the simulation
17. Execute NAM on the trace file
18. Observe the simulated events on the NAM editor and packet flow on link G to r
19. View the trace file and analyse the events
20. Stop
49
Program
#G acts as a gateway
set G [$ns node]
#r acts as a receiver
set r [$ns node]
#Define the queue size for the link between node G and r
$ns queue-limit $G $r 5
50
#Create a TCP agent and attach it to node s1
set tcp1 [new Agent/TCP/Reno]
$ns attach-agent $s1 $tcp1
$tcp1 set window_ 8
$tcp1 set fid_ 1
51
#Define label for nodes
$ns at 0.0 "$s1 label Sender1"
$ns at 0.0 "$s2 label Sender2"
$ns at 0.0 "$s3 label Sender3"
$ns at 0.0 "$G label Gateway"
$ns at 0.0 "$r label Receiver"
52
Output
$ ns TCP.tcl
Result
Thus the behaviour of TCP was observed and the basic terminologies of TCP
transmission were understood.
53
Exp# 8a Distance Vector Routing Protocol
Date:
Aim
To simulate a link failure and to observe distance vector routing protocol in action.
Algorithm
1. Create a simulator object
2. Set routing protocol to Distance Vector routing
3. Trace packets on all links onto NAM trace and text trace file
4. Define finish procedure to close files, flush tracing and run NAM
5. Create eight nodes
6. Specify the link characteristics between nodes
7. Describe their layout topology as a octagon
8. Add UDP agent for node n1
9. Create CBR traffic on top of UDP and set traffic parameters.
10. Add a sink agent to node n4
11. Connect source and the sink
12. Schedule events as follows:
a. Start traffic flow at 0.5
b. Down the link n3-n4 at 1.0
c. Up the link n3-n4 at 2.0
d. Stop traffic at 3.0
e. Call finish procedure at 5.0
13. Start the scheduler
14. Observe the traffic route when link is up and down
15. View the simulated events and trace file analyze it
16. Stop
54
Program
# Open tracefile
set nt [open trace.tr w]
$ns trace-all $nt
# Create 8 nodes
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]
set n8 [$ns node]
55
# specify layout as a octagon
$ns duplex-link-op $n1 $n2 orient left-up
$ns duplex-link-op $n2 $n3 orient up
$ns duplex-link-op $n3 $n4 orient right-up
$ns duplex-link-op $n4 $n5 orient right
$ns duplex-link-op $n5 $n6 orient right-down
$ns duplex-link-op $n6 $n7 orient down
$ns duplex-link-op $n7 $n8 orient left-down
$ns duplex-link-op $n8 $n1 orient left
#Schedule events for the CBR agent and the network dynamics
$ns at 0.0 "$n1 label Source"
$ns at 0.0 "$n4 label Destination"
$ns at 0.5 "$cbr0 start"
$ns rtmodel-at 1.0 down $n3 $n4
$ns rtmodel-at 2.0 up $n3 $n4
$ns at 4.5 "$cbr0 stop"
56
Output
$ ns distvect.tcl
57
Result
Thus, performance of distance vector protocol and routing path was studied using NS2.
58
Exp. No. 8b Link State Routing Protocol
Date:
Aim
To simulate a link failure and to observe link state routing protocol in action.
Algorithm
1. Create a simulator object
2. Set routing protocol to Link State routing
3. Trace packets on all links onto NAM trace and text trace file
4. Define finish procedure to close files, flush tracing and run NAM
5. Create twelve nodes
6. Specify the link characteristics between nodes
7. Describe their layout topology in an adhoc manner.
8. Create CBR traffic on top of UDP and set traffic parameters.
9. Create source and sink and connect them
10. Schedule events as follows:
a. Start traffic flows at 1.0 and 2.0
b. Down the link n5-n11 at 10.0 and restore it at 30.0
c. Down the link n7-n6 at 15.0 and restore it at 20.0
d. Call finish procedure at 45.0
11. Start the scheduler
12. Observe the traffic route when link is up and down
13. View the simulated events and trace file analyze it
14. Stop
59
Program
60
$ns rtproto LS
$ns at 45 "finish"
$ns run
Output
$ ns ls.tcl
61
Result:
Thus performance of link state protocol and its routing path was simulated using NS2.
62
Exp# 10 CRC Error Detection
Date:
Aim
To detect whether the given data is corrupted or not using CRC method.
Algorithm
1. Read number of data bits.
2. Read the data bit-by-bit
3. Read number of divisor bits
4. Enter the divisor bit-by-bit
5. Append zeroes to the message
6. Generate remainder by using XOR division
7. Subtract remainder from message using XOR
8. Display the CRC code word
9. Accept transmitted message as receiver side data
10. Peroform polynomial division using XOR
11. If remainder is zero then display “No error” else display “Error”
12. Stop
63
Program
import java.io.*;
class crc_gen
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
int[] data;
int[] div;
int[] divisor;
int[] rem;
int[] crc;
int data_bits, divisor_bits, tot_length;
tot_length=data_bits+divisor_bits-1;
div=new int[tot_length];
rem=new int[tot_length];
crc=new int[tot_length];
64
rem=divide(div, divisor, rem);
System.out.println();
System.out.println("CRC code : ");
for(int i=0;i<crc.length;i++)
System.out.print(crc[i]);
/*-------------------ERROR DETECTION---------------------*/
System.out.println();
System.out.println("Enter CRC code of " + tot_length
+ " bits : ");
for(int i=0; i<crc.length; i++)
crc[i]=Integer.parseInt(br.readLine());
if((rem.length-cur)<divisor.length)
break;
}
return rem;
65
}
}
Output
$javac crc_gen.java
$java crc_gen
Enter number of data bits :
8
Enter data bits :
1
0
0
1
1
0
1
0
Enter no. of bits in divisor:
4
Enter Divisor bits :
1
1
0
1
Dividend (after appending 0's): 10011010000
CRC code :
10011010101
Enter CRC code of 11 bits :
1
0
0
1
1
0
1
0
1
0
1
No Error
Result
Thus error detection is done using cyclic redundancy check method.
66