CN Lab
CN Lab
AIM:
To Learn to use commands like tcpdump, netstat , ifconfig, nslookup and traceroute ping.
COMMANDS:
1. Tcpdump:
The tcpdump utility allows you to capture packets that flow within your network to assist in
network troubleshooting. The following are several examples of using tcpdump with different options.
Traffic is captured based on a specified filter.
1
# tcpdump dst port http
2.Netstat :
Netstat is a common command line TCP/IP networking available in most versions of
Windows, Linux, UNIX and other operating systems.
Netstat provides information and statistics about protocols in use and current TCP/IP network
connections. The Windows help screen (analogous to a Linux or UNIX for netstat reads as follows:
displays protocol statistics and current TCP/IP network connections.
#netstat
3.ipconfig :
In Windows, ipconfig is a console application designed to run from the Windows command
prompt. This utility allows you to get the IP address information of a Windows computer. Using
ipconfig .
From the command prompt, type ipconfig to run the utility with default options. The output
of the default command contains the IP address, network mask, and gateway for all physical and
virtual network adapter.
2
#ipconfig
4.nslookup :
The nslookup (which stands for name server lookup) command is a network utility program
used to obtain information about internet servers. It finds name server information for domains by
querying the Domain Name System.
The nslookup command is a powerful tool for diagnosing DNS problems. You know you're
experiencing a DNS problem when you can access a resource by specifying its IP address but not its
DNS name.
#nslookup
5.Trace route:
Traceroute uses Internet Control Message Protocol (ICMP) echo packets with variable time to
live (TTL) values. The response time of each hop is calculated. To guarantee accuracy, each hop is
queried multiple times (usually three times) to better measure the response of that particular hop.
Traceroute is a network diagnostic tool used to track the pathway taken by a packet on an IP
network from source to destination. Traceroute also records the time taken for each hop the packet
makes during its route to the destination. Traceroute uses Internet Control Message Protocol (ICMP)
echo packets with variable time to live (TTL) values.
The response time of each hop is calculated. To guarantee accuracy, each hop is queried
multiple times (usually three times) to better measure the response of that particular hop. Traceroute
3
sends packets with TTL values that gradually increase from packet to packet, starting with TTL value
of one. Routers decrement TTL values of packets by one when routing and discard packets whose TTL
value has reached zero, returning the ICMP error message ICMP Time Exceeded.
For the first set of packets, the first router receives the packet, decrements the TTL value and
drops the packet because it then has TTL value zero. The router sends an ICMP Time Exceeded
message back to the source. The next set of packets are given a TTL value of two, so the first router
forwards the packets, but the second router drops them and replies with ICMP Time Exceeded.
Proceeding in this way, traceroute uses the returned ICMP Time Exceeded messages to build a list of
routers that packets traverse, until the destination is reached and returns an ICMP Echo Reply
message.
With the tracert command shown above, we're asking tracert to show us the path from the local
computer all the way to the network device with the hostname
www.google.com.
#tracert google.com
RESULT:
Thus the various networks commands like tcpdump, netstat, ifconfig, nslookup and traceroute
ping are executed successfully.
4
Ex no:
Write a HTTP web client program to download a web
Date: page using TCP sockets
AIM:
To write a java program for socket for HTTP for web page upload and download .
ALGORITHM:
Client:
Step 1: Start the program.
Step 2: Create a socket which binds the IP address of server and the port address to acquire service.
Step 3: After establishing connection send the url to server.
Step 4: Open a file and store the received data into the file.
Step 5: Close the socket.
Step 6: End the program.
Server:
Step 1: Start the program.
Step 2: Create a server socket to activate the port address.
Step 3: Create a socket for the server socket which accepts the connection.
Step 4: After establishing connection receive url from client.
Step 5: Download the content of the url received and send the data to client.
Step 6: Close the socket.
Step 7: End the program
PROGRAM :
Client :
import javax.swing.*;
import java.net.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
5
import java.io.IOException;
import javax.imageio.ImageIO;
public class Client
{
public static void main(String args[]) throws Exception
{
Socket soc;
BufferedImage img = null;
soc=new Socket("localhost",4000);
System.out.println("Client is running. ");
try
{
System.out.println("Reading image from disk. ");
Img=ImageIO.read(newFile("digital_image_processing.jpg"));
ByteArrayOutputStreambaos = new ByteArrayOutputStream();
ImageIO.write(img, "jpg", baos);
baos.flush();
byte[] bytes = baos.toByteArray(); baos.close();
System.out.println("Sending image to server.");
OutputStream out = soc.getOutputStream();
DataOutputStream dos = new DataOutputStream(out);
dos.writeInt(bytes.length);
dos.write(bytes, 0, bytes.length);
System.out.println("Image sent to
server."); dos.close(); out.close();
}
catch (Exception e)
{
System.out.println("Exception: " + e.getMessage());
soc.close();
}
soc.close();
}
}
6
Server :
import java.net.*;
import java.io.*;
import
java.awt.image.*;
import
javax.imageio.*;
import javax.swing.*;
class Server
{
public static void main(String args[]) throws Exception
{
ServerSocket server=null;
Socket socket;
server=new ServerSocket(4000);
System.out.println("Server Waiting for image");
socket=server.accept(); System.out.println("Client connected.");
InputStream in = socket.getInputStream();
DataInputStream dis = new DataInputStream(in);
int len = dis.readInt();
System.out.println("Image Size: " + len/1024 + "KB"); byte[] data = new byte[len];
dis.readFully(data);
dis.close();
in.close();
InputStream ian = new ByteArrayInputStream(data);
BufferedImage bImage = ImageIO.read(ian);
JFrame f = new JFrame("Server");
ImageIcon icon = new
ImageIcon(bImage); JLabel l = new
JLabel(); l.setIcon(icon);
f.add(l);
f.pack();
f.setVisible(true);
}
}
7
OUTPUT:
Server waiting for image
Client connected
Image size:29KB
RESULT:
Thus the socket program for HTTP for web page upload and download was developed and
executed successfully.
8
Ex no: Applications using TCP sockets like:
a)Echo client and echo server
Date: b)Chat
AIM :
To write a java program for application using TCP Sockets Links
ALGORITHM :
Client :
Step 1: Start
Step 2: Create the TCP socket
Step 3: Establish connection with the server
Step 4: Get the message to be echoed from the user
Step 5: Send the message to the server
Step 6: Receive the message echoed by the server
Step 7: Display the message received from the server
Step 8: Terminate the connection
Step 9: Stop
Server :
Step 1: Start
Step 2: Create TCP socket, make it a listening socket
Step 3: Accept the connection request sent by the client for connection establishment
Step 4: Receive the message sent by the client
Step 5: Display the received message
Step 6: Send the received message to the client from which it receives
Step 7: Close the connection when client initiates termination and server becomes a listening server,
waiting for clients.
Step8: Stop.
9
PROGRAM:
EchoServer.java :
import java.net.*;
import java.io.*;
public class EServer
{
public static void main(String args[])
{
ServerSocket s=null;
String line;
DataInputStream is;
PrintStream ps;
Socket c=null;
try
{
s=new ServerSocket(9000);
}
catch(IOException e)
{
System.out.println(e);
}
try
{
c=s.accept();
is=new DataInputStream(c.getInputStream());
ps=new PrintStream(c.getOutputStream());
while(true)
{
line=is.readLine();ps.pri
ntln(line);
}
}
10
catch(IOException e)
{
System.out.println(e);
}
}
}
EchoClient.java:
import java.net.*;
import java.io.*;
public class
EClient
{
public static void main(String arg[])
{
Socket c=null;
String line;
DataInputStream is,is1;
PrintStream os;
try
{
InetAddress ia = InetAddress.getLocalHost();
c=new Socket(ia,9000);
}
catch(IOException)
{
System.out.println(e);
}
try
{
os=new PrintStream(c.getOutputStream());
is=new DataInputStream(System.in);
is1=new
DataInputStream(c.getInputStream));
while(true)
{
11
System.out.println("Client:");
line=is.readLine()os.println(line);
System.out.println("Server:" + is1.readLine());
}
}
catch(IOException e)
{
System.out.println("Socke
Closed!");
}
}
}
OUTPUT
Server :
C:\Program Files\Java\jdk1.5.0\bin>javac EServer.java
C:\Program Files\Java\jdk1.5.0\bin>java EServer
C:\Program Files\Java\jdk1.5.0\bin>
Client :
C:\Program Files\Java\jdk1.5.0\bin>javac EClient.java
C:\Program Files\Java\jdk1.5.0\bin>java EClient
Client: Hai Server
Server:Hai Server
Client: Hello
Server:Hello
Client:end
Server:ed
Client:ds
Socket
Closed!
b) Chat :
ALGORITHM :
12
Client :
Step 1: Start
Step 2: Create the UDP datagram socket
Step 3: Get the request message to be sent from the user
Step 4: Send the request message to the server
Step 5: If the request message is ―END‖ go to step 10
Step 6: Wait for the reply message from the server
Step 7: Receive the reply message sent by the server
Step 8: Display the reply message received from the server
Step 9: Repeat the steps from 3 to 8
Step 10: Stop
Server :
Step1: Start
Step2: Create UDP datagram socket, make it a listening socket
Step 3: Receive the request message sent by the client
Step 4: If the received message is ―END‖ go to step 10
Step 5: Retrieve the client‘s IP address from the request message received
Step 6: Display the received message
Step 7: Get the reply message from the user 8. Send the reply message to the client 9. Repeat the steps
from 3 to 8.
Step 8: Stop.
PROGRAM :
UDPserver.java :
import java.io.*;
import java.net.*;
class UDPserver
{
public static DatagramSocket ds; public static byte
buffer[]=new byte[1024];
public static int clientport=789,serverport=790;
13
public static void main(String args[])throws
Exception
{
ds=new DatagramSocket(clientport);
System.out.println("press ctrl+c to quit the program");
BufferedReader dis=new BufferedReader(new InputStreamReader(System.in));
InetAddress ia=InetAddress.getLocalHost();
while(true)
{
DatagramPacket p=new DatagramPacket(buffer,buffer.length); ds.receive(p);
String psx=new String(p.getData(),0,p.getLength());
System.out.println("Client:" + psx);
System.out.println("Server:");
String str=dis.readLine();
if(str.equals("end"))
break;
buffer=str.getBytes();
ds.send(new DatagramPacket(buffer,str.length(),ia,serverport));
}
}
}
UDPclient.java:
14
byte buffer[]=new byte[1024];
ds=new
DatagramSocket(serverport);
BufferedReader dis=new BufferedReader(new InputStreamReader(System.in));
System.out.println("server waiting");
InetAddress ia=InetAddress.getLocalHost();
while(true)
{
System.out.println("Client);
String str=dis.readLine();
if(str.equals("end"))
break;
buffer=str.getBytes(); ds.send(new
DatagramPacket(buffer,str.length(),ia,clientport));
DatagramPacket p=new
DatagramPacket(buffer,buffer.length); ds.receive(p);
String psx=new String(p.getData(),0,p.getLength());
System.out.println("Server:" +psx);
}
}
}
OUTPUT:
Server :
15
Client :
C:\Program Files\Java\jdk1.5.0\bin>javac
UDPclient.java C:\Program
Files\Java\jdk1.5.0\bin>java UDPclient server waiting
Client:Hai Server
Server:Hello Client
Client:How are You
Server:I am Fine
Client:end ;
E:\nwlab>
RESULT:
Thus the java application program using TCP Sockets was developed and executed
successfully.
16
Ex no:
Simulation of DNS using UDP Sockets
Date:
AIM :
To write a java program for DNS application .
ALGORITHM :
Server :
Step 1: Start
Step 2: Create UDP datagram socket
Step 3: Create a table that maps host name and IP address
Step 4: Receive the host name from the client
Step 5: Retrieve the client‘s IP address from the received datagram 6.
Get the IP address mapped for the host name from the table.
Step 6: Display the host name and corresponding IP address
Step 7: Send the IP address for the requested host name to the client
Step 8: Stop.
Client :
Step 1: Start
Step 2: Create UDP datagram socket.
Step 3: Get the host name from the client
Step 4: Send the host name to the server
Step 5: Wait for the reply from the server
Step 6: Receive the reply datagram and read the IP address for the requested host name 7.
Display the IP address.
Step 7: Stop.
PROGRAM :
DNS Server :
29
java import java.io.*; import
java.net.*;
public class udpdnsserver
{
private static int indexOf(String[] array, String str)
{
str = str.trim();
for (int i=0; i < array.length; i++)
{
if (array[i].equals(str)) return i;
}
return -1;
}
public static void main(String arg[])throws IOException {
String[] hosts = {"yahoo.com", "gmail.com","cricinfo.com", "facebook.com"};
String[] ip = {"68.180.206.184", "209.85.148.19","80.168.92.140", "69.63.189.16"};
System.out.println("Press Ctrl + C to Quit");
while (true)
{
DatagramSocket serversocket=new DatagramSocket(1362);
byte[] senddata = new byte[1021];
byte[] receivedata = new byte[1021];
DatagramPacket recvpack = new DatagramPacket(receivedata, receivedata.length);
serversocket.receive(recvpack);
String sen = new String(recvpack.getData());
InetAddress ipaddress = recvpack.getAddress();
int port = recvpack.getPort();
String capsent;
System.out.println("Request for host " + sen);
if(indexOf (hosts, sen) != -1)
capsent = ip[indexOf (hosts, sen)];
else capsent = "Host Not Found";
senddata = capsent.getBytes();
DatagramPacket pack = new DatagramPacket (senddata,
senddata.length,ipaddress,port); serversocket.send(pack); serversocket.close();
}
30
}
}
Senddata = sentence.getBytes();
31
OUTPUT:
Sever:
javac udpdnsserver.java java
udpdnsserver
Press Ctrl + C to Quit Request for host yahoo.com
Request for host cricinfo.com Request for
host youtube.com
Client :
>javac udpdnsclient.java
>java udpdnsclient
Enter the hostname : yahoo.com
IP Address: 68.180.206.184
>java udpdnsclient
Enter the hostname : cricinfo.com
IP Address: 80.168.92.140
>java udpdnsclient
Enter the hostname : youtube.com
IP Address: Host Not Found
RESULT:
Thus the java application program using UDP Sockets to implement DNS was developed
and executed successfully.
32
Ex no:
AIM:
To write a java program for simulating ARP and RARP protocols using TCP.
ALGORITHM:
Client :
Server:
PROGRAM :
33
Client:
import java.io.*;
import java.net.*;
import java.util.*;
class Clientarp
{
public static void main(String args[])
{ try {
BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); Socket
clsct=new Socket("127.0.0.1",139)
DataInputStream din=new DataInputStream(clsct.getInputStream());
DataOutputStream dout=new DataOutputStream(clsct.getOutputStream());
System.out.println("Enter the Logical address(IP):");
String str1=in.readLine();
dout.writeBytes(str1+'\n'; String
str=din.readLine();
System.out.println("The Physical
Address is: "+str); clsct.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
}
Server:
import java.io.*; import
java.net.*; import
java.util.*;
class Serverarp
{
public static void main(String args[])
{
try
{
34
ServerSocket obj=new
ServerSocket(139);
Socket obj1=obj.accept();
while(true)
{
DataInputStream din=new DataInputStream(obj1.getInputStream());
DataOutputStream dout=new DataOutputStream(obj1.getOutputStream());
String str=din.readLine();
String ip[]={"165.165.80.80","165.165.79.1"};
String mac[]={"6A:08:AA:C2","8A:BC:E3:FA"};
for(int i=0;i<ip.length;i++)
{
if(str.equals(ip[i]))
{
dout.writeBytes(mac[i]+'\n'); break;
}
}
obj.close();
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
OUTPUT:
E:\networks>java Serverarp
E:\networks>java Clientarp Enter
the Logical address(IP):
165.165.80.80
The Physical Address is: 6A:08:AA:C2
35
b) Program for Reverse Address Resolution Protocol (RARP) using UDP
ALGORITHM:
Client :
Step 1: Start the program
Step 2: Create datagram socket
Step 3: Get the MAC address to be converted into IP address from the user.
Step 4: Send this MAC address to server using UDP datagram.
Step 5:Receive the datagram from the server and display the corresponding IP address.
Step 6: Stop
Server :
Step 1: Start the program.
Step 2: Server maintains the table in which IP and corresponding MAC addresses are stored.
Step 3: Create the datagram socket
Step 4: Receive the datagram sent by the client and read the MAC address sent.
Step 5: Retrieve the IP address for the received MAC address from the table.
Step 6: Display the corresponding IP address.
Step 7: Stop
PROGRAM:
Client:
import java.io.*; import
java.net.*; import
java.util.*;
class Clientrarp12
{
public static void main(String args[])
{
try
{
DatagramSocket client=new DatagramSocket();
InetAddress addr=InetAddress.getByName("127.0.0.1");
byte[] sendbyte=new byte[1024];
byte[] receivebyte=new byte[1024];
36
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Physical address (MAC):")
String str=in.readLine(); sendbyte=str.getBytes();
DatagramPacket sender=newDatagramPacket(sendbyte,sendbyte.length,addr,1309);
client.send(sender);
DatagramPacket receiver=new DatagramPacket(receivebyte,receivebyte.length);
client.receive(receiver);
String s=new String(receiver.getData());
System.out.println("The Logical Address is(IP): "+s.trim());
client.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Server:
import java.io.*; import
java.net.*; import
java.util.*;
class Serverrarp12
{
public static void main(String args[])
{
try
{
DatagramSocket server=new DatagramSocket(1309); while(true)
{
byte[] sendbyte=new byte[1024];
byte[] receivebyte=new byte[1024];
DatagramPacket receiver=new DatagramPacket(receivebyte,receivebyte.length);
server.receive(receiver);
String str=new String(receiver.getData());
37
String s=str.trim();
InetAddress addr=receiver.getAddress();
int port=receiver.getPort();
String ip[]={"165.165.80.80","165.165.79.1"};
String mac[]={"6A:08:AA:C2","8A:BC:E3:FA"};
for(int i=0;i<ip.length;i++)
{
if(s.equals(mac[i]))
{
sendbyte=ip[i].getBytes();
DatagramPacket sender = new
DatagramPacket(sendbyte,sendbyte.length,addr,port);
server.send(sender);
break;
}
}
break;
}
}
}catch(Exception e)
{
System.out.println(e);
}
}
}
OUTPUT:
I:\ex>java Serverrarp12
I:\ex>java Clientrarp12
Enter the Physical address (MAC):
6A:08:AA:C2
The Logical Address is(IP): 165.165.80.80
RESULT :
Thus the program for implementing to display simulating ARP and RARP protocols was executed
successfully and output is verified.
38
Ex no:
Study of Network simulator(NS) and simulation of
Date: congestion control algorithm using NS
AIM:
To Study Network simulator (NS).and Simulation of Congestion Control Algorithms using NS .
Theory:
Network Simulator (Version 2), widely known as NS2, is simply an event drivensimulation tool
that has proved useful in studying the dynamic nature of communication networks. Simulation of
wired as well as wireless network functions and protocols (e.g., routing algorithms, TCP, UDP)
can be done using NS2. In general, NS2 provides users with a way of specifying such network
protocols and simulating their corresponding behaviors. Due to its flexibility and modular nature,
NS2 has gained constant popularity in the networking research community since its birth in 1989.
The above figure shows the basic architecture of NS2. NS2 provides users with
an executable command ns which 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
39
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.
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 simplicit.
It is not necessary to declare a data type for variable prior to the usage.
Basics of TCL:
Hello World!
puts stdout{Hello, World!}
Hello ,World!
Variables:
Command Substitution set a 5
set len [string length foobar] set b $a
set len [expr [string length foobar] + 9]
Simple Arithmetic:
\ expr 7.2 / 4 51
Procedures
proc Diag {a b} {
40
set c [expr sqrt($a * $a + $b * $b)]
return $c }
puts ―Diagonal of a 3, 4 right triangle is [Diag 3 4]ۅ
NS Simulator Preliminaries:
1. Initialization and termination aspects of the ns simulator.
2. Definition of network nodes, links, queues and topology.
3. Definition of agents and of applications.
4. The nam visualization tool.
5. Tracing and random variables.
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 ―nam file respectively. Remark that
they begins with a # symbol.The second line open the file ―out.tr ۅto be used for writing, declared
with the letter ―wۅ.The third line uses a simulator method called trace-all that have as parameter
the name of the file where the traces will go. The last line tells the simulator to record all simulation
traces in NAM input format. It also gives the file name that the trace will be written to later by the
command $ns flush-trace. In our case, this will be the file pointed at by the pointer ―$namfile ,i.e
the file ―out.trۅ. The termination of the program is done using a ―finish procedure.
41
#Define a ‘finish’ procedure
Proc finish { } {
global ns tracefile1 namfile
$ns flush-trace
Close $tracefile1
Close $namfile
Exec nam out.nam &
Exit 0
The word proc declares a procedure in this case called finish and without arguments. The
word global is used to tell that we are using variables declared outside the procedure. The simulator
method ―flush-trace” will dump the traces on the respective files. The tcl command ―close”
closes the trace files defined before and exec executes the nam program for visualization.
The command exit will ends the application and return the number 0 as status to the
system. Zero is the default for a clean exit. Other values can be used to say that is a exit because
something fails.
At the end of ns program we should call the procedure ―finish ۅand specify at what time
the termination should occur. For example,
$ns at 125.0 “finish”
will be used to call ―finish ۅat time 125sec.Indeed,the at method of the simulator allows
us to schedule events explicitly.
The simulation can then begin using the command
$ns run
42
Which means that $n0 and $n2 are connected using a bi-directional link that has 10ms of
propagation delay and a capacity of 10Mb per sec for each direction. To define a directional link
instead of a bi-directional one, we should replace “duplexlink” by “simplex link”.
In NS, an output queue of a node is implemented as a part of each link whose input is that
node. The definition of the link then includes the way to handle overflow at that queue.
In our case, if the buffer capacity of the output queue is exceeded then the last packet to
arrive is dropped. Many alternative options exist, such as the RED (Random Early Discard)
mechanism, the FQ (Fair Queuing), the DRR (Deficit Round Robin), the stochastic Fair Queuing
(SFQ) and the CBQ (which including a priority and a round-robin scheduler).
In ns, an output queue of a node is implemented as a part of each link whose input is that
node. We should also define the buffer capacity of the queue related to each link. An example
would be:
Defines the behavior of the destination node of TCP and assigns to it a pointer called sink
#Setup a UDP connection
set udp [new Agent/UDP]
$ns attach-agent $n1 $udp
set null [new Agent/Null]
$ns attach-agent $n5 $null
$ns connect $udp $null
$udp set fid_2
43
set cbr [new Application/Traffic/CBR]
$cbr attach-agent $udp
$cbr set packetsize_ 100
$cbr set rate_ 0.01Mb
$cbr set random_ false
Above shows the definition of a CBR application using a UDP agent. The command
$ns attach-agent $n4 $sink defines the destination node. The command $ns connect $tcp $sink
finally makes the TCP connection between the source and destination nodes.TCP has many
parameters with initial fixed defaults values that can be changed ifmentioned 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.
Result :
Thus the Network Simulator 2 is studied in detail.
44
Ex no Study of TCP/UDP performance using
AIM:
To simulate the performance of TCP/UDP using NS2.
STUDY – 1 TCP
The transmission Control Protocol (TCP) is one of the most important protocols of Internet
Protocols suite. It is most widely used protocol for data transmission in communication network such as
internet.
Features
TCP is reliable protocol. That is, the receiver always sends either positive or negative
acknowledgement about the data packet to the sender, so that the sender always has bright clue about
whether the data packet is reached the destination or it needs to resend it.
• TCP ensures that the data reaches intended destination in the same order it was sent.
• TCP is connection oriented. TCP requires that connection between two remote points be
established before sending actual data.
• TCP provides error-checking and recovery mechanism.
• TCP provides end-to-end communication.
• TCP provides flow control and quality of service. • TCP operates in Client/Server point-to-
point mode.
• TCP provides full duplex server, i.e. it can perform roles of both receiver and sender.
Header:
The length of TCP header is minimum 20 bytes long and maximum 60 bytes.
• Source Port (16-bits) - It identifies source port of the application process on the sending
device.
• Destination Port (16-bits) - It identifies destination port of the application process on the
receiving device.
• Sequence Number (32-bits) - Sequence number of data bytes of a segment in a session.
• Acknowledgement Number (32-bits) - When ACK flag is set, this number contains the
next sequence number of the data byte expected and works as acknowledgement of the previous
data received.
• Data Offset (4-bits) - This field implies both, the size of TCP header (32- bit words) and the
offset of data in current packet in the whole TCP segment.
45
• Reserved (3-bits) - Reserved for future use and all are set zero by default.
• Flags (1-bit each) o NS - Nonce Sum bit is used by Explicit Congestion Notification signaling
process.
CWR - When a host receives packet with ECE bit set, it sets Congestion Windows Reduced to
acknowledge that ECE received.
ECE -It has two meanings:
If SYN bit is clear to 0, then ECE means that the IP packet has its CE (congestion
experience) bit set.
If SYN bit is set to 1, ECE means that the device is ECT capable.
URG - It indicates that Urgent Pointer field has significant data and should be processed.
ACK - It indicates that Acknowledgement field has significance. If ACK is cleared to 0, it
indicates that packet does not contain any acknowledgement.
PSH - When set, it is a request to the receiving station to PUSH data (as soon as it comes) to the
receiving application without buffering it.
RST - Reset flag has the following features:
It is used to refuse an incoming connection.
It is used to reject a segment.
It is used to restart a connection.
SYN - This flag is used to set up a connection between hosts.
FIN - This flag is used to release a connection and no more data is exchanged thereafter. Because
packets with SYN and FIN flags have sequence numbers, they are processed in correct order.
• Windows Size - This field is used for flow control between two stations and indicates the amount of
buffer (in bytes) the receiver has allocated for a segment, i.e. how much data is the receiver expecting.
• Checksum - This field contains the checksum of Header, Data and Pseudo Headers.
• Urgent Pointer - It points to the urgent data byte if URG flag is set to 1.
• Options - It facilitates additional options which are not covered by the regular header. Option field is
always described in 32-bit words. If this field contains data less than 32bit, padding is used to cover the
remaining bits to reach 32-bit boundary.
Addressing
TCP communication between two remote hosts is done by means of port numbers (TSAPs). Ports
numbers can range from 0 – 65535 which are divided as:
• System Ports (0 – 1023)
• User Ports ( 1024 – 49151)
• Private/Dynamic Ports (49152 – 65535)
46
Connection
Management TCP communication works in Server/Client model. The client initiates the connection
and the server either accepts or rejects it. Three-way handshaking is used for connection management.
Establishment
Client initiates the connection and sends the segment with a Sequence number. Server acknowledges it
back with its own Sequence number and ACK of client’s segment which is one more than client’s
Sequence number. Client after receiving ACK of its segment sends an acknowledgement of Server’s
response.
Release
Either of server and client can send TCP segment with FIN flag set to 1. When the receiving end
responds it back by Acknowledging FIN, that direction of TCP communication is closed and connection is
released.
Bandwidth Management
TCP uses the concept of window size to accommodate the need of Bandwidth management. Window
size tells the sender at the remote end, the number of data byte segments the receiver at this end can
receive. TCP uses slow start phase by using window size 1 and increases the window size exponentially
after each successful communication.
For example, the client uses windows size 2 and sends 2 bytes of data. When the acknowledgement of
this segment received the windows size is doubled to 4 and next sent the segment sent will be 4 data bytes
long. When the acknowledgement of 4-byte data segment is received, the client sets windows size to 8 and
so on.
If an acknowledgement is missed, i.e. data lost in transit network or it received NACK, then the
window size is reduced to half and slow start phase starts again.
47
Multiplexing
The technique to combine two or more data streams in one session is called Multiplexing. When a TCP
client initializes a connection with Server, it always refers to a welldefined port number which indicates the
application process. The client itself uses a randomly generated port number from private port number pools.
Using TCP Multiplexing, a client can communicate with a number of different application process in a
single session. For example, a client requests a web page which in turn contains different types of data
(HTTP, SMTP, FTP etc.) the TCP session timeout is increased and the session is kept open for longer time so
that the three-way handshake overhead can be avoided.
This enables the client system to receive multiple connection over single virtual connection. These
virtual connections are not good for Servers if the timeout is too long.
Congestion Control
When large amount of data is fed to system which is not capable of handling it, congestion occurs. TCP
controls congestion by means of Window mechanism. TCP sets a window size telling the other end how
much data segment to send. TCP may use three algorithms for congestion control:
• Additive increase, Multiplicative Decrease
• Slow Start
• Timeout React
Timer Management
TCP uses different types of timer to control and management various tasks:
Keep-alive timer
• This timer is used to check the integrity and validity of a connection.
• When keep-alive time expires, the host sends a probe to check if the connection still exists.
Retransmission timer
• This timer maintains stateful session of data sent.
• If the acknowledgement of sent data does not receive within the Retransmission time, the data
segment is sent again.
Persist timer
• TCP session can be paused by either host by sending Window Size 0.
• To resume the session a host needs to send Window Size with some larger value. 63
• If this segment never reaches the other end, both ends may wait for each other for infinite time.
• Persist Timer helps avoid deadlocks in communication.
Timed-Wait
• After releasing a connection, either of the hosts waits for a Timed-Wait time to terminate the
connection completely.
48
• This is in order to make sure that the other end has received the acknowledgement of its connection
termination request.
• Timed-out can be a maximum of 240 seconds (4 minutes).
Crash Recovery
TCP is very reliable protocol. It provides sequence number to each of byte sent in segment. It
provides the feedback mechanism i.e. when a host receives a packet, it is bound to ACK that packet having
the next sequence number expected (if it is not the last segment).
When a TCP Server crashes mid-way communication and re-starts its process it sends TPDU
broadcast to all its hosts. The hosts can then send the last data segment which was never unacknowledged
and carry onwards.
STUDY – 2 UDP
The User Datagram Protocol (UDP) is simplest Transport Layer communication protocol
available of the TCP/IP protocol suite. It involves minimum amount of communication mechanism. UDP is
said to be an unreliable transport protocol but it uses IP services which provides best effort delivery
mechanism.
In UDP, the receiver does not generate an acknowledgement of packet received and in turn, the
sender does not wait for any acknowledgement of packet sent. This shortcoming makes this protocol
unreliable as well as easier on processing.
Requirement of UDP:
A question may arise, why do we need an unreliable protocol to transport the data? We
deploy UDP where the acknowledgement packets share significant 64 amount of bandwidth along with the
actual data. For example, in case of video streaming, thousands of packets are forwarded towards its users.
Acknowledging all the packets is troublesome and may contain huge amount of bandwidth wastage. The best
delivery mechanism of underlying IP protocol ensures best efforts to deliver its packets, but even if some
packets in video streaming get lost, the impact is not calamitous and can be ignored easily. Loss of few
packets in video and voice traffic sometimes goes unnoticed.
Features :
• UDP is used when acknowledgement of data does not hold any significance.
• UDP is good protocol for data flowing in one direction.
• UDP is simple and suitable for query based communications.
• UDP is not connection oriented.
• UDP does not provide congestion control mechanism.
49
• UDP does not guarantee ordered delivery of data.
• UDP is stateless.
• UDP is suitable protocol for streaming applications such as VoIP, multimedia streaming.
UDP Header :
• Source Port - This 16 bits information is used to identify the source port of the packet.
• Destination Port - This 16 bits information, is used identify application level service on destination
machine.
• Length - Length field specifies the entire length of UDP packet (including header). It is 16-bits field
and minimum value is 8-byte, i.e. the size of UDP header itself.
• Checksum - This field stores the checksum value generated by the sender before sending. IPv4 has
this field as optional so when checksum field does not contain any value it is made 0 and all its bits are set
to zero.
UDP application
Here are few applications where UDP is used to transmit data:
• Domain Name Services
• Simple Network Management Protocol
• Trivial File Transfer Protocol
• Routing Information Protocol
• Kerberos
RESULT :
50
Ex.No:
Simulation of Distance Vector/ Link State
Date: Routing algorithm.
AIM:
To simulate the Distance vector and link state routing protocols using NS2.
ALGORITHM:
Step 1: Create a Simulator object.
Step 2: Set routing as dynamic.
Step 3: Open the trace and nam trace files.
Step 4: Define the finish procedure.
Step 5: Create nodes and the links between them.
Step 6: Create the agents and attach them to the nodes.
Step 7: Create the applications and attach them to the udp agent.
Step 8: Connect udp and null..
Step 9: At 1 sec the link between node 1 and 2 is broken.
Step 10: At 2 sec the link is up again.
Step 11: Run the simulation.
51
} for {set i 0} {$i <7}
{incr i} { set n($i) [$ns
node]
52
Output:
53
Distance Vector Routing Protocol
ALGORITHM:
Step 1: Create a simulator object
Step 2: Set routing protocol to Distance Vector routing
Step 3: Trace packets on all links onto NAM trace and text trace file
Step 4: Define finish procedure to close files, flush tracing and run NAM
Step 5: Create eight nodes
Step 6: Specify the link characteristics between nodes
Step 7: Describe their layout topology as a octagon
Step 8: Add UDP agent for node n1
Step 9: Create CBR traffic on top of UDP and set traffic parameters.
Step 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
Step 11: Start the scheduler
Step 12: Observe the traffic route when link is up and down
Step 13: View the simulated events and trace file analyze it
Step 14: Stop
PROGRAM
54
{ global ns nf $ns flush-
trace #Close the
trace file close $nf
#Execute nam on the trace file
exec nam -a out.nam & exit
0
}
# 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] # Specify link
characterestics
$ns duplex-link $n1 $n2 1Mb 10ms DropTail
$ns duplex-link $n2 $n3 1Mb 10ms DropTail
$ns duplex-link $n3 $n4 1Mb 10ms DropTail
$ns duplex-link $n4 $n5 1Mb 10ms DropTail $ns
duplex-link $n5 $n6 1Mb 10ms DropTail $ns
duplex-link $n6 $n7 1Mb 10ms DropTail
$ns duplex-link $n7 $n8 1Mb 10ms DropTail
$ns duplex-link $n8 $n1 1Mb 10ms DropTail
# 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
#Create a UDP agent and attach it to node n1
set udp0 [new Agent/UDP] $ns attach-agent
$n1 $udp0
#Create a CBR traffic source and attach it to udp0 set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0
#Create a Null agent (a traffic sink) and attach it to node n4
set null0 [new Agent/Null] $ns
attach-agent $n4 $null0
55
#Connect the traffic source with the traffic sink
$ns connect $udp0 $null0
#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"
#Call the finish procedure after 5 seconds of simulation time
$ns at 5.0 "finish"
#Run the simulation
$ns run
OUTPUT :
$ ns distvect.tcl
56
57
RESULT:
Thus the simulation for Distance vector and link state routing protocols was done using NS2.
58
Ex no: Performance Evaluation of Routing protocols using
Simulation tool.
Date:
AIM:
To write a ns2 program for implementing unicast routing protocol.
ALGORITHM:
Step 1: Start the program.
Step 2: Declare the global variables ns for creating a new simulator.
Step 3: Set the color for packets.
Step 4: Open the network animator file in the name of file2 in the write mode.
Step 5: Open the trace file in the name of file 1 in the write mode.
Step 6: Set the unicast routing protocol to transfer the packets in network.
Step 7: Create the required no of nodes.
Step 8: Create the duplex-link between the nodes including the delay time,bandwidth and dropping queue
mechanism.
Step 9: Give the position for the links between the nodes.
Step 10: Set a tcp reno connection for source node.
Step 11: Set the destination node using tcp sink.
Step 12: Setup a ftp connection over the tcp connection.
Step 13: Down the connection between any nodes at a particular time.
Step 14: Reconnect the downed connection at a particular time.
Step 15: Define the finish procedure.
Step 16: In the definition of the finish procedure declare the global variables ns, file1, and file2.
Step 17: Close the trace file and name file and execute the network animation file.
Step 18: At the particular time call the finish procedure. 19. Stop the program.
PROGRAM:
59
$ns color 2 Red #Open the
Trace file set file1 [open
out.tr w] $ns trace-all $file1
#Open the NAM trace file
set file2 [open out.nam w]
$ns namtrace-all $file2
#Define a 'finish' procedure
proc finish {}
{ global ns file1 file2 $ns
flush-trace close
$file1 close $file2
exec nam out.nam &
exit 3
}
# Next line should be commented out to have the static routing
$ns rtproto DV
#Create six nodes
set n0 [$ns node] set
n1 [$ns node] set n2
[$ns node] set n4
[$ns node] set n4
[$ns node] set n5
[$ns node]
#Create links between the nodes
$ns duplex-link $n0 $n1 0.3Mb 10ms DropTail
$ns duplex-link $n1 $n2 0.3Mb 10ms DropTail
$ns duplex-link $n2 $n3 0.3Mb 10ms DropTail
$ns duplex-link $n1 $n4 0.3Mb 10ms DropTail
$ns duplex-link $n3 $n5 0.5Mb 10ms DropTail
$ns duplex-link $n4 $n5 0.5Mb 10ms DropTail
60
$ns duplex-link-op $n3 $n5 orient left-up $ns
duplex-link-op $n4 $n5 orient right-up
61
62
(b) Multicasting Routing Protocol
AIM:
To write a ns2 program for implementing multicasting routing protocol.
ALGORITHM:
PROGRAM:
# Create scheduler
#Create an event scheduler wit multicast turned on set
ns [new Simulator -multicast on]
#$ns multicast
63
#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
64
$udp0 set dst_addr_ $group1 $udp0 set
dst_port_ 0 set cbr1 [new
Application/Traffic/CBR] $cbr1 attach-
agent $udp0
# Schedule events
65
$ns at 0.5 "$cbr1 start" $ns
at 9.5 "$cbr1 stop" $ns at
0.5 "$cbr2 start" $ns at 9.5
"$cbr2 stop"
#post-processing $ns
at 10.0 "finish" proc
finish {}
{
global ns tf $ns
flush-trace
close $tf
exec nam mcast.nam &
exit 0
}
# For nam
#Colors for packets from two mcast groups
$ns color 10 red
$ns color 11 green
$ns color 30 purple $ns
color 31 green
66
# 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
# Animation rate
$ns set-animation-rate 3.0ms
$ns run
67
68
RESULT:
Thus the case study about the different routing algorithms to select the network path with its
optimum and economical during data transfer is done.
69
Ex no:
Implementation of Error Detection Code (like CRC)
Date:
AIM:
ALGORITHM:
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;
70
int[] crc;
int data_bits, divisor_bits, tot_length;
System.out.println("Enter number of data bits : ");
data_bits=Integer.parseInt(br.readLine()); data=new int[data_bits];
System.out.println("Enter data bits : ");
for(int i=0; i<data_bits; i++)
data[i]=Integer.parseInt(br.readLine());
System.out.println("Enter number of bits in divisor : ");
divisor_bits=Integer.parseInt(br.readLine()); divisor=new int[divisor_bits];
System.out.println("Enter Divisor bits : ");
for(int i=0; i<divisor_bits; i++)
divisor[i]=Integer.parseInt(br.readLine();
System.out.print("Data bits are : "); for(int
i=0; i< data_bits; i++)
System.out.print(data[i]);
System.out.println();
System.out.print("divisor bits are : "); for(int
i=0; i< divisor_bits; i++)
System.out.print(divisor[i]);
System.out.println();
tot_length=data_bits+divisor_bits-1;
div=new int[tot_length]; rem=new
int[tot_length];
crc=new int[tot_length];
for(int i=0;i<data.length;i++)
div[i]=data[i];
System.out.print("Dividend (after appending 0's) are : ");
for(int i=0; i< div.length; i++)
System.out.print(div[i]);
System.out.println();
for(int j=0; j<div.length; j++)
{
rem[j] = div[j];
}
rem=divide(div, divisor, rem);
71
for(int i=0;i<div.length;i++)
{
crc[i]=(div[i]^rem[i]);
}
System.out.println();
System.out.println("CRC code : "); for(int
i=0;i<crc.length;i++)
System.out.print(crc[i]);
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());
System.out.print("crc bits are : ");
for(int i=0; i< crc.length; i++)
System.out.print(crc[i]);
System.out.println();
for(int j=0; j<crc.length; j++)
{
rem[j] = crc[j];
}
rem=divide(crc, divisor, rem);
for(int i=0; i< rem.length; i++)
{
if(rem[i]!=0)
{
System.out.println("Error");
break;
}
if(i==rem.length-1)
System.out.println("No Error");
}
System.out.println("THANK YOU. .... )");
}
static int[] divide(int div[],int divisor[], int rem[])
{ int cur=0; while(true)
{
72
for(int i=0;i<divisor.length;i++)
rem[cur+i]=(rem[cur+i]^divisor[i]);
while(rem[cur]==0 && cur!=rem.length-1)
cur++;
if((rem.length-cur)<divisor.length)
break;
}
return rem;
}
}
OUTPUT :
RESULT:
Thus the above program for error checking code using was executed successfully.
74
75