Cs8581 Networks Lab Student
Cs8581 Networks Lab Student
ENGINEERING
CS3591-COMPUTER NETWORKS
Semester V
1
TABLE OF CONTENTS
2
NPR College of Engineering & Technology, Natham.
VISION
• To develop students with intellectual curiosity and technical expertise to meet the global
needs.
MISSION
3
Department of Computer Science and Engineering
Vision:
Mission:
• To establish conducive academic environment by imparting quality education and value added
training.
• To encourage students to develop innovative projects to optimally resolve the challenging social
problems.
• PEO1: develop into the most knowledgeable professional to pursue higher education and
Research or have a successful carrier in industries.
• PEO2: Successfully carry forward domain knowledge in computing and allied areas to solve
complex and real world engineering problems.
• PEO3: Meet the technological revolution they are continuously upgraded with the technical
knowledge.
• PEO4: Serve the humanity with social responsibility combined with ethics
• PSO 1: The ability to deal with real time problems by understand, the evolutionary changes in
computing, apply standard practices and strategies in software project development using open-
ended programming environments.
• PSO 2: The ability to employ modern computer languages, environments, and platforms in
creating innovative career paths to be an entrepreneur, pursue lifelong professional development
in computingand also to act as a good citizen by inculcating in them moral values & ethics.
4
CS3591 COMPUTER NETWORKS LTPC
3 02 4
OBJECTIVES
• To understand the concept of layering in networks.
• To know the functions of protocols of each layer of TCP/IP protocol suite.
• To visualize the end-to-end flow of information.
• To learn the functions of network layer and the various routing protocols
• To familiarize the functions and protocols of the Transport layer
LIST OF EXPERIMENTS
1. Learn to use commands like tcpdump, netstat, ifconfig, nslookup and traceroute. Capture
ping and trace route PDUs using a network protocol analyzer and examine.
2. Write a HTTP web client program to download a web page using TCP sockets.
3. Applications using TCP sockets like: a) Echo client and echo server b) Chat
4. Simulation of DNS using UDP sockets.
5. Use a tool like Wireshark to capture packets and examine the packets
6. Write a code simulating ARP /RARP protocols.
7. Study of Network simulator (NS) and Simulation of Congestion Control Algorithms using
NS.
8. Study of TCP/UDP performance using Simulation tool.
9. Simulation of Distance Vector/ Link State Routing algorithm.
10. Simulation of an error correction code (like CRC)
TOTAL: 30 PERIODS
COURSE OUTCOMES:
5
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
CS3591 – COMPUTER NETWORKS
Course Outcomes
After completion of the course, Students are able to learn the listed Course Outcomes.
Knowledge
Cos Course Code Course Outcomes
Level
CO1 C301.1 Explain the basic layers and its functions in computer networks. K2
Understand the basics of how data flows from one node to
CO2 C301.2 K2
another.
Exp.
Name of the Experiment COs POs PSOs
No.
1. Commands and network protocols. CO1 1,2,3&12 1 ,2
2. HTTP web client program -TCP sockets. CO1 1,2,3,5& 11 1,2
3. Applications using TCP sockets. CO1
CO2 1,2,3,9,12 1
CO3
4. DNS using UDP sockets. CO2 1,2,4,5,11 &
2
CO3 12
5. Use a tool like Wireshark to capture packets and
CO3
1,2,3,4 & 11 1,2
examine the packets CO4
6. ARP / RARP protocols. CO3 1,2,3,4 &11 1,2
7. Study of Network simulator (NS). CO5 1,8,9 & 10 1,3
8. Study of TCP/UDP performance CO1
1,2,5 & 11 1,2
CO2
9. Simulation of Distance Vector/ Link State Routing
CO3
1,3,5 & 11 1,2
algorithm. CO4
10. Error correction code.
CO5 1,2 &12 1,2
Additional Experiments
6
11. Simulation of Go Back N protocol CO3
1,2,3,5& 11 1,2 &3
CO5
12. Carrier Sense Multiple Access 1,2,3,5,6,11
CO5 1,2&3
& 12
Program Outcomes
7
EX.NO:1 Date:
Learn to use commands like tcpdump, netstat, ifconfig, nslookup and traceroute.
Capture ping and traceroute PDUs using a network protocol analyzer and examine.
AIM:
To Learn to use commands like tcpdump, netstat, ifconfig, nslookup and traceroute ping.
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.
Netstat
ipconfig
ipconfigis 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.
From the command prompt, type ipconfigto 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.
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.
Trace route:
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
8
Commands:
Tcpdump:
Display traffic between 2 hosts:
To display all traffic between two hosts (represented by variables host1 and host2): #
tcpdump host host1 and host2
Display traffic from a source or destination host only:
To display traffic from only a source (src) or destination (dst) host:
# tcpdumpsrc host
# tcpdumpdst host
Display traffic for a specific protocol
Provide the protocol as an argument to display only traffic for a specific protocol, for
example tcp, udp, icmp, arp
# tcpdump protocol
For example to display traffic only for the tcptraffic :
# tcpdumptcp
Filtering based on source or destination port
To filter based on a source or destination port:
# tcpdumpsrc port ftp
# tcpdumpdst 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
9
3. ipconfig
In Windows, ipconfigis 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.
#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 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. 12
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.
10
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
6.Ping:
The ping command sends an echo request to a host available on the network.
Using this command, you can check if your remote host is responding well or not.
Tracking and isolating hardware and software problems. Determining the status of the
network and various foreign hosts. The ping command is usually used as a simple way
to verify that a computer can communicate over the network with another computer or
network device. The ping command operates by sending Internet Control Message
Protocol (ICMP) Echo Request messages to the destination computer and waiting for a
response
# ping172.16.6.2
1. Define network
2. Define network topology
3. What is OSI Layers.
4. What is the use of netstat command?
5. What is nslookup command?
6. What is the purpose of traceroute command?
7. What is ping command.
RESULT:
Thus the various networks commands like tcpdump, netstat, ifconfig, nslookup and
traceroute ping are executed successfully.
11
Ex.No: 2 Date :
Write a HTTP web client program to download a web page using TCP sockets
AIM:
To write a java program for socket for HTTP for web page upload and download .
ALGORITHM:
Client:
1. Start.
2. Create socket and establish the connection with the server.
3. Read the image to be uploaded from the disk
4. Send the image read to the server
5. Terminate the connection
6. Stop.
Server:
1. Start
2. Create socket, bind IP address and port number with the created socket and make server a
listening server.
3. Accept the connection request from the client
4. Receive the image sent by the client.
5. Display the image.
6. Close the connection.
7. Stop.
PROGRAM
Client
importjavax.swing.*; i
mport java.net.*;
importjava.awt.image.*;
importjavax.imageio.*;
import java.io.*;
importjava.awt.image.BufferedImage;
importjava.io.ByteArrayOutputStream;
importjava.io.File; import java.io.IOException;
importjavax.imageio.ImageIO;
public class Client { public static void main(String args[]) throws Exception {
Socket soc; BufferedImageimg = null;
soc=new Socket("localhost",4000);
System.out.println("Client is running. ");
try { System.out.println("Reading image from disk. ");
img = ImageIO.read(new File("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();
12
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();
}}
Server:
import java.net.*;
import java.io.*;
importjava.awt.image.*;
importjavax.imageio.*;
importjavax.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);
intlen = dis.readInt();
System.out.println("Image Size: " + len/1024 + "KB");
byte[] data = new byte[len];
dis.readFully(data);
dis.close();
in.close();
InputStreamian = new ByteArrayInputStream(data);
BufferedImagebImage = ImageIO.read(ian);
JFrame f = new JFrame("Server");
ImageIcon icon = new ImageIcon(bImage);
JLabel l = new JLabel();
l.setIcon(icon); f.add(l);
0f.pack();
f.setVisible(true);
}
}
13
OUTPUT:
RESULT:
Thus the socket program for HTTP for web page upload and download was developed and executed
successfully.
14
Ex.No: 3 Date:
Applications using TCP sockets like: Echo client and echo server, Chat and File Transfer
AIM:
To write a client-server application for Echo client and echo server,chat and file transfer
using TCP
a)Echo client & echo server
ALGORITHM:
CLIENT SIDE
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;
PrintStreamps;
Socket c=null;
try
{
s=new ServerSocket(9000);
}
catch(IOException e)
15
{
System.out.println(e);
}
try
{
c=s.accept();
is=new DataInputStream(c.getInputStream());
ps=new PrintStream(c.getOutputStream());
while(true)
{
line=is.readLine();
ps.println(line);
}
}
catch(IOException e)
{
System.out.println(e);
}} }
EClient.java
import java.net.*;
import java.io.*;
public class EClient
{ public static void main(String arg[])
{
Socket c=null;
String line;
DataInputStream is,is1;
PrintStreamos;
try
{
InetAddressia = InetAddress.getLocalHost();
c=new Socket(ia,9000);
}
catch(IOException e)
{
System.out.println(e);
}
try
{
os=new PrintStream(c.getOutputStream());
is=new DataInputStream(System.in);
is1=new DataInputStream(c.getInputStream());
while(true)
{
System.out.println("Client:");
line=is.readLine();
os.println(line);
System.out.println("Server:" + is1.readLine());
}
16
}
catch(IOException e)
{
System.out.println("Socket Closed!");
}}}
OUTPUT
B) Chat:
CLIENT
SERVER
Program
UDPserver.java
import java.io.*;
import java.net.*;
class UDPserver
{
public static DatagramSocket ds;
public static byte buffer[]=new byte[1024];
public static intclientport=789,serverport=790;
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));
InetAddressia=InetAddress.geyLocalHost();
while(true)
17
{
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
18
C)File transfer:
CLIENT SIDE
1. Start.
2. Establish a connection between the Client and Server.
3. Socket ss=new Socket(InetAddress.getLocalHost(),1100);
4. Implement a client that can send two requests.
i) To get a file from the server.
ii) To put or send a file to the server.
5. After getting approval from the server ,the client either get file from the server or send
6. file to the server.
SERVER SIDE
1. Start.
2. Implement a server socket that listens to a particular port number.
3. Server reads the filename and sends the data stored in the file for the‘get’ request.
4. It reads the data from the input stream and writes it to a file in theserver for the ‘put’
instruction.
5. Exit upon client’s request.
6. Stop.
Program
File Server :
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket
public class FileServer
{
public static void main(String[] args) throws Exception
{
//Initialize Sockets
ServerSocketssock = new ServerSocket(5000); Socket
socket = ssock.accept();
//The InetAddress specification
InetAddress IA = InetAddress.getByName("localhost");
//Specify the file
File file = new File("e:\\Bookmarks.html");
FileInputStreamfis = new FileInputStream(file);
BufferedInputStreambis = new BufferedInputStream(fis); //Get
19
socket's output stream
OutputStreamos = socket.getOutputStream(); //Read
File Contents into contents array
byte[] contents;
long fileLength = file.length();
long current = 0;
long start = System.nanoTime();
while(current!=fileLength){
int size = 10000;
if(fileLength - current >= size)
current += size;
else{
size = (int)(fileLength - current);
current = fileLength;
}
contents = new byte[size];
bis.read(contents, 0, size);
os.write(contents);
System.out.print("Sending file ... "+(current*100)/fileLength+"% complete!");
}
os.flush();
//File transfer done. Close the socket connection!
socket.close();
ssock.close();
System.out.println("File sent succesfully!");
}}
File Client:
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.Socket;
public class FileClient {
public static void main(String[] args) throws Exception{
//Initialize socket
Socket socket = new Socket(InetAddress.getByName("localhost"), 5000); byte[]
contents = new byte[10000];
//Initialize the FileOutputStream to the output file's full path. FileOutputStreamfos = new
FileOutputStream("e:\\Bookmarks1.html");
BufferedOutputStreambos = new BufferedOutputStream(fos);
InputStream is = socket.getInputStream();
//No of bytes read in one read() call
intbytesRead = 0;
while((bytesRead=is.read(contents))!=-1)
bos.write(contents, 0, bytesRead);
bos.flush();
socket.close();
20
System.out.println("File saved successfully!");
}
}
Output
Result:
21
Ex.No: 4 Date:
AIM:
To write a program to Simulation of DNS using UDP sockets.
ALGORITHM:
DNS Server
22
DatagramPacketrecvpack = new DatagramPacket(receivedata, receivedata.length);
serversocket.receive(recvpack);
String sen = new String(recvpack.getData());
InetAddressipaddress = 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();
}}}
UDP DNS Client
java import java.io.*;
import java.net.*;
public class udpdnsclient
{
public static void main(String args[])throws IOException
{
BufferedReaderbr = new BufferedReader(new InputStreamReader(System.in));
DatagramSocketclientsocket = new DatagramSocket();
InetAddressipaddress;
if (args.length == 0)
ipaddress = InetAddress.getLocalHost();
else
23
ipaddress = InetAddress.getByName(args[0]);
byte[] senddata = new byte[1024];
byte[] receivedata = new byte[1024];
intportaddr = 1362;
System.out.print("Enter the hostname : ");
String sentence = br.readLine();
Senddata = sentence.getBytes();
DatagramPacket pack = new DatagramPacket(senddata,senddata.length,
ipaddress,portaddr);
clientsocket.send(pack);
DatagramPacketrecvpack =new DatagramPacket(receivedata,receivedata.length);
clientsocket.receive(recvpack);
String modified = new String(recvpack.getData());
System.out.println("IP Address: " + modified);
clientsocket.close();
}}
OUTPUT
Result:
24
Ex.No:5 Date:
Use a tool like Wireshark to capture packets and examine the packets
AIM:
Use a tool like Wireshark to capture packets and examine the packets
25
Wireshark Network Analyzer:
Home Page
Display Filters
26
Capturing Local Area Connection
Result:
The simulation of Wireshark to capture packets and examine the packets was executed
successfully.
27
Ex.No:6 Date:
AIM
ALGORITHM:
CLIENT SIDE
1. Establish a connection between the Client and Server.
Socket ss=new Socket(InetAddress.getLocalHost(),1100);
2. Create instance output stream writer
PrintWriter ps=new PrintWriter(s.getOutputStream(),true);
3. Get the IP Address to resolve its physical address.
4. Send the IPAddress to its output Stream.ps.println(ip);
5. Print the Physical Address received from the server.
SERVER SIDE
1. Accept the connection request by the client.
ServerSocket ss=new ServerSocket(2000);Socket s=ss.accept();
2. Get the IPaddress from its inputstream.
BufferedReader br1=new BufferedReader(newInputStreamReader(s.getInputStream()));
ip=br1.readLine();
3. During runtime execute the processRuntime r=Runtime.getRuntime();
Process p=r.exec("arp -a "+ip);
4. Send the Physical Address to the client.
Program
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());
DataOutputStreamdout=new DataOutputStream(clsct.getOutputStream());
System.out.println("Enter the Logical address(IP):");
28
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{
ServerSocketobj=new
ServerSocket(139); Socket
obj1=obj.accept();
while(true)
{
DataInputStream din=new DataInputStream(obj1.getInputStream());
DataOutputStreamdout=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:
29
(b) Program for Reverse Address Resolution Protocol (RARP) using UDP
ALGORITHM:
CLIENT
SERVER
Program
Client:
import java.io.*;
import java.net.*;
import java.util.*;
class Clientrarp12
{
public static void main(String args[])
{
try
{
DatagramSocket client=new DatagramSocket();
InetAddressaddr=InetAddress.getByName("127.0.0.1");
byte[] sendbyte=new byte[1024];
byte[] receivebyte=new byte[1024];
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);
30
}}}
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());
String s=str.trim();
InetAddressaddr=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:
Result:
Thus the java code to simulate ARP/RARP protocols was executed successfully
31
Ex.No: 7 Date:
AIM:
using NS
Ns Overview
Ns Status
Platform support
Ns functionalities
Slow start
NS(Network Simulators)
Most of the commercial simulators are GUI driven, while some network simulators are CLI
driven. The network model / configuration describes the state of the network (nodes,routers,
switches, links) and the events (data transmissions, packet error etc.). An important output of
simulations are the trace files. Trace files log every packet, every event that occurred in the
32
simulation and are used for analysis. Network simulators can also provide other tools to facilitate
visual analysis of trends and potential trouble spots.
Most network simulators use discrete event simulation, in which a list of pending "events" is
stored, and those events are processed in order, with some events triggering future events—such as
the event of the arrival of a packet at one node triggering the event of the arrival of that packet at a
downstream node. Simulation of networks is a very complex task. For example, if congestion is high,
then estimation of the average occupancy is challenging because of high variance. To estimate the
like lihood of a buffer overflow in a network, the time required for an accurate answer can be
extremely large. Specialized techniques such as "control variates" and "importance sampling" have
been developed to speed simulation.
There are many both free/open-source and proprietary network simulators. Examples of
notable network simulation software are, ordered after how often they are mentioned in research
papers:
1. ns (open source)
Network simulators serve a variety of needs. Compared to the cost and time involved in
setting up an entire test bed containing multiple networked computers, routers and data links,
network simulators are relatively fast and inexpensive. They allow engineers, researchers to test
scenarios that might be particularly difficult or expensive to emulate using real hardware - for
instance, simulating a scenario with several nodes or experimenting with a new protocol in the
network. Network simulators are particularly useful in allowing researchers to test new networking
protocols or changes to existing protocols in a controlled and reproducible environment. A typical
network simulator encompasses a wide range of networking technologies and can help the users to
build complex networks from basic building blocks such as a variety of nodes and links. With the
help of simulators, one can design hierarchical networks using various types of nodes like computers,
hubs, bridges, routers, switches, links, mobile units etc.
33
Various types of Wide Area Network (WAN) technologies like TCP, ATM, IP etc. and Local
Area Network (LAN) technologies like Ethernet, token rings etc., can all be simulated with a typical
simulator and the user can test, analyze various standard results apart from devising some novel
protocol or strategy for routing etc. Network simulators are also widely used to simulate 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
Packet loss 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
Throughput 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. Throughput is usually
measured in bitsper second (bit/s orbs), and sometimes in data packets per second or data packets per
time slot. These measures 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.
34
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 highband widths. 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.
Slow-start is used in conjunction with other algorithms to avoid sending more data than the
network is capable of transmitting, that is, to avoid causing network congestion. The additive
increase/multiplicative decrease (AIMD) algorithm is a feedback control algorithm. AIMD
combines linear growth of the congestion window with an exponential reduction when a congestion
takes place. Multiple flows using AIMD congestion control will eventually converge to use equal
amounts of a contended link. Fast Retransmit is an enhancement to TCP that reduces the time a
sender waits before retransmitting a lost segment.
Program:
include <wifi_lte/wifi_lte_rtable.h>
structr_hist_entry *elm, *elm2;
intnum_later = 1;
elm = STAILQ_FIRST(&r_hist_);
while (elm != NULL &&num_later<= num_dup_acks_){
num_later;
elm = STAILQ_NEXT(elm, linfo_);
}
if (elm != NULL){
elm = findDataPacketInRecvHistory(STAILQ_NEXT(elm,linfo_));
if (elm != NULL){
elm2 = STAILQ_NEXT(elm, linfo_);
while(elm2 != NULL){
if (elm2->seq_num_ <seq_num&& elm2->t_recv_ <
35
time){
STAILQ_REMOVE(&r_hist_,elm2,r_hist_entry,linfo_);
delete elm2;
} else
elm = elm2;
elm2 = STAILQ_NEXT(elm, linfo_);
}
}
}
}
voidDCCPTFRCAgent::removeAcksRecvHistory(){
structr_hist_entry *elm1 = STAILQ_FIRST(&r_hist_);
structr_hist_entry *elm2;
intnum_later = 1;
while (elm1 != NULL &&num_later<= num_dup_acks_){
num_later;
elm1 = STAILQ_NEXT(elm1, linfo_);
}
if(elm1 == NULL)
return;
elm2 = STAILQ_NEXT(elm1, linfo_);
while(elm2 != NULL){
if (elm2->type_ == DCCP_ACK){
STAILQ_REMOVE(&r_hist_,elm2,r_hist_entry,linfo_);
delete elm2;
} else {
elm1 = elm2;
}
elm2 = STAILQ_NEXT(elm1, linfo_);
}
}
inline r_hist_entry
*DCCPTFRCAgent::findDataPacketInRecvHistory(r_hist_entry *start){
while(start != NULL && start->type_ == DCCP_ACK)
start = STAILQ_NEXT(start,linfo_);
return start;
}
36
VIVA (Pre and Post Lab) QUESTIONS:
3. What is a node?
Result:
Thus we have Studied Network simulator (NS) and Simulation of Congestion Control
Algorithms using NS.
37
Ex.No: 8 Date:
AIM:
• 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.
• 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.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.
• UDP does not guarantee ordered delivery of data.
• UDP is stateless.
• UDP is suitable protocol for streaming applications such as VoIP, multimedia streaming.
38
TCP Performance
Algorithm
PROGRAM:
39
$ns duplex-link-op $n2 $n3 orient right
$ns duplex-link-op $n2 $n3 queuePos 0.5
set tcp [new Agent/TCP]
$tcp set class_ 1
set sink [new Agent/TCPSink]
$ns attach-agent $n1 $tcp
$ns attach-agent $n3 $sink
$ns connect $tcp $sink
set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ns at 1.2 "$ftp start"
$ns at 1.35 "$ns detach-agent $n1 $tcp ; $ns detach-agent $n3 $sink"
$ns at 3.0 "finish"
proc finish {} {
global ns f nf
$ns flush-trace
close $f
close $nf
puts "Running nam.."
exec xgraph tcpout.tr -geometry 600x800 &
exec namtcpout.nam&
exit 0
}
$ns run
Output
40
UDP Performance
ALGORITHM :
$ns trace-all $f
41
$ns duplex-link-op $n0 $n2 orient right-up
proc finish {} {
global ns f nf
42
$ns flush-trace
close $f
close $nf
exec namudpout.nam&
exit 0
$ns run
Output:
5. What is TCP?
RESULT :
43
Ex.No: 9 Date:
AIM:
To simulate the Distance vector and link state routing protocols using NS2.
Routing is the process of selecting best paths in a network. In the past, the term routing was also used
to mean forwarding network traffic among networks. However this latter function is much better
described as simply forwarding. Routing is performed for many kinds of networks, including the
telephone network (circuit switching), electronic data networks (such as the Internet), and
transportation networks. This article is concerned primarily with routing in electronic data networks
using packet switching technology.
In packet switching networks, routing directs packet forwarding (the transit of logically addressed
network packets from their source toward their ultimate destination) through intermediate nodes.
Intermediate nodes are typically network hardware devices such as routers, bridges, gateways,
firewalls, or switches. General-purpose computers can also forward packets and perform routing,
though they are not specialized hardware and may suffer from limited performance. The routing
process usually directs forwarding on the basis of routing tables which maintain a record of the
routes to various network destinations.
Thus, constructing routing tables, which are held in the router's memory, is very important for
efficient routing. Most routing algorithms use only one network path at a time. Multipath routing
techniques enable the use of multiple alternative paths.
In case of overlapping/equal routes, the following elements are considered in order to decide which
routes get installed into the routing table (sorted by priority):
1. Prefix-Length: where longer subnet masks are preferred (independent of whether it is within a
routing protocol or over different routing protocol)
2. Metric: where a lower metric/cost is preferred (only valid within one and the same routing
protocol)
3. Administrative distance: where a lower distance is preferred (only valid between different routing
protocols) Routing, in a more narrow sense of the term, is often contrasted with bridging in its
assumption that network addresses are structured and that similar addresses imply proximity within
the network. Structured addresses allow a single routing table entry to represent the route to a group
of devices. In large networks, structured addressing (routing, in the narrow sense) outperforms
unstructured addressing (bridging). Routing has become the dominant form of addressing on the
Internet. Bridging is still widely used within localized environments.
44
b. Flooding
Flooding is a simple routing algorithm in which every incoming packet is sent through
every outgoing link except the one it arrived on. Flooding is used in bridging and in systems such
as Usenet and peer-to-peer file sharing and as part of some routing protocols, including OSPF,
DVMRP, and those used in ad-hoc wireless networks.There are generally two types of flooding
available, Uncontrolled Flooding and Controlled Flooding. Uncontrolled Flooding is the fatal
law of flooding. All nodes have neighbours and route packets indefinitely. More than two
Controlled Flooding has its own two algorithms to make it reliable, SNCF (Sequence
Number Controlled Flooding) and RPF (Reverse Path Flooding). In SNCF, the node attaches its
own address and sequence number to the packet, since every node has a memory of addresses
and sequence numbers. If it receives a packet in memory, it drops it immediately while in RPF,
the node will only send the packet forward. If it is received from the next node, it sends it back to
the sender.
class being the link-state protocol. Distance-vector routing protocols use the Bellman–Ford
algorithm, Ford–Fulkerson algorithm, or DUAL FSM (in the case of Cisco Systems's protocols)
to calculate paths.
A distance-vector routing protocol requires that a router informs its neighbors of topology
changes periodically. Compared to link-state protocols, which require a router to inform all the
The term distance vector refers to the fact that the protocol manipulates vectors (arrays)
of distances to other nodes in the network. The vector distance algorithm was the original
ARPANET routing algorithm and was also used in the internet under the name of RIP (Routing
45
Information Protocol).Examples of distance-vector routing protocols include RIPv1 and RIPv2
and IGRP.
Method
Routers using distance-vector protocol do not have knowledge of the entire path to a
Distance-vector protocols are based on calculating the direction and distance to any link
in a network. "Direction" usually means the next hop address and the exit interface. "Distance" is
a measure of the cost to reach a certain node. The least cost route between any two nodes is the
route with minimum distance. Each node maintains a vector (table) of minimum distance to
every node. The cost of reaching a destination is calculated using various route metrics. RIP uses
the hop count of the destination whereas IGRP takes into account other information such as node
router's routing table is sent to all its neighbors that are configured to use the same distancevector
routing protocol. RIP supports cross-platform distance vector routing whereas IGRP is a
Cisco Systems proprietary distance vector routing protocol. Once a router has this information it
is able to amend its own routing table to reflect the changes and then inform its neighbors of the
changes. This process has been described as ‗routing by rumor‘ because routers are relying on
the information they receive from other routers and cannot determine if the information is
actually valid and true. There are a number of features which can be used to help with instability
EGP and BGP are not pure distance-vector routing protocols because a distance-vector
protocol calculates routes based only on link costs whereas in BGP, for example, the local route
Count-to-infinity problem
46
The Bellman–Ford algorithm does not prevent routing loops from happening and suffers
from the count-to-infinity problem. The core of the count-to-infinity problem is that if A tells B
that it has a path somewhere, there is no way for B to know if the path has B as a part of it. To
see the problem clearly, imagine a subnet connected like A–B–C–D–E–F, and let the metric
between the routers be "number of jumps". Now suppose that A is taken offline. In the vectorupdate-
process B notices that the route to A, which was distance 1, is down – B does not receive
the vector update from A. The problem is, B also gets an update from C, and C is still not aware
of the fact that A is down – so it tells B that A is only two jumps from C (C to B to A), which is
false. This slowly propagates through the network until it reaches infinity (in which case the
ALGORITHM:
PROGRAM
ALGORITHM:
49
PROGRAM
$ns rtproto DV
# Open tracefile
proc finish {}
global ns nf
$ns flush-trace
close $nf
exit 0
# Create 8 nodes
50
set n3 [$ns node]
51
$ns attach-agent $n1 $udp0
#Schedule events for the CBR agent and the network dynamics
$ns run
OUTPUT
52
VIVA (Pre &Post Lab) Questions:
4. What os OSPF
RESULT:
Thus the simulation for Distance vector and link state routing protocols was done using
NS2.
53
Ex.No:10 Date:
AIM:
The cyclic redundancy check, or CRC, is a technique for detecting errors in digital data, but not for
making corrections when errors are detected. It is used primarily in data transmission. In the CRC
method, a certain number of check bits, often called a checksum, are appended to the message being
transmitted. The receiver can determine whether or not the check bits agree with the data, to ascertain
with a certain degree of probability whether or not an error occurred in transmission.
CRC involves binary division of the data bits being sent by a predetermined divisor agreed upon by
the communicating system. The divisor is generated using polynomials. So, CRC is also called
polynomial code checksum.
CRC uses Generator Polynomial which is available on both sender and receiver side. An example
generator polynomial is of the form like x3 + x + 1. This generator polynomial represents key 1011.
Another example is x2 + 1 that represents key 101.
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
Perform modulo-2 division again and if remainder is 0, then there are no errors.
Modulo 2 Division:
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.
54
ALGORITHM:
2. Given a bit string, append 0S to the end of it (the number of 0s is the same as the degree
3. Divide B(x) by some agreed on polynomial G(x) (generator polynomial) and determine
7. Let T’ represent the bit stream the receiver gets and T’(x) the associated polynomial. The
and no error occurred otherwise, the receiver concludes an error occurred and requires a
retransmission
PROGRAM:
import java.io.*;
class crc_gen
{
public static void main(String args[]) throws IOException {
BufferedReaderbr=new BufferedReader(new InputStreamReader(System.in));
int[] data;
int[] div;
int[] divisor;
int[] rem;
int[] crc;
intdata_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());
55
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];
/*------------------ CRC GENERATION-----------------------*/
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);
for(int i=0;i<div.length;i++)
{
//append dividend and remainder
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]);
/*-------------------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());
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");
56
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)
{
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.
57
TOPIC BEYOND SYLLABUS
AIM:
ALGORITHM :
2. Each frame in the buffer has a sequence number starting from 1 and increasing up to the
window size.
3. The source node has a window i.e. a buffer to store the frames. This buffer size is the
58
number of frames to be transmitted continuously.
5. For the first frame, the receiving node forms a positive acknowledgement if the frame is
6. If subsequent frames are received without error (up to window size) cumulative positive
acknowledgement is formed.
7. If the subsequent frame is received with error, the cumulative acknowledgment error-free
frames are transmitted. If in the same window two frames or more frames are received
with error, the second and the subsequent error frames are neglected. Similarly even the
frames received without error after the receipt of a frame with error are neglected.
8. The source node retransmits all frames of window from the first error frame.
9. If the frames are errorless in the next transmission and if the acknowledgment is error
free, the window slides by the number of error-free frames being transmitted.
10. If the acknowledgment is transmitted with error, all the frames of window at source are
11. This concept of repeating the transmission from the first error frame in the window is
PROGRAM :
59
$ns at 0.0 "$n3 label SYS3"
$ns at 0.0 "$n4 label SYS4"
$ns at 0.0 "$n5 label SYS5"
set nf [open goback.nam w] $ns namtrace-all $nf
set f [open goback.tr w] $ns trace-all $f
$ns duplex-link $n0 $n2 1Mb 20ms DropTail $ns duplex-link-op $n0 $n2 orient right-down $ns
queue-limit $n0 $n2 5
$ns duplex-link $n1 $n2 1Mb 20ms DropTail $ns duplex-link-op $n1 $n2 orient right-up $ns
duplex-link $n2 $n3 1Mb 20ms DropTail $ns duplex-link-op $n2 $n3 orient right
$ns duplex-link $n3 $n4 1Mb 20ms DropTail $ns duplex-link-op $n3 $n4 orient right-up $ns
duplex-link $n3 $n5 1Mb 20ms DropTail $ns duplex-link-op $n3 $n5 orient right-down
Agent/TCP set_nam_tracevar_true
set tcp [new Agent/TCP] $tcp set fid 1
$ns attach-agent $n1 $tcp
set sink [new Agent/TCPSink] $ns attach-agent $n4 $sink $ns connect $tcp $sink
set ftp [new Application/FTP] $ftp attach-agent $tcp
$ns at 0.05 "$ftp start"
$ns at 0.06 "$tcp set windowlnit 6"
$ns at 0.06 "$tcp set maxcwnd 6"
$ns at 0.25 "$ns queue-limit $n3 $n4 0"
$ns at 0.26 "$ns queue-limit $n3 $n4 10"
$ns at 0.305 "$tcp set windowlnit 4"
$ns at 0.305 "$tcp set maxcwnd 4"
$ns at 0.368 "$ns detach-agent $n1 $tcp ; $ns detach-agent $n4 $sink"
$ns at 1.5 "finish"
$ns at 0.0 "$ns trace-annotate \"Goback N end\""
$ns at 0.05 "$ns trace-annotate \"FTP starts at 0.01\""
$ns at 0.06 "$ns trace-annotate \"Send 6Packets from SYS1 to SYS4\""
$ns at 0.26 "$ns trace-annotate \"Error Occurs for 4th packet so not sent ack for the Packet\""
60
$ns at 0.30 "$ns trace-annotate \"Retransmit Packet_4 to 6\""
$ns at 1.0 "$ns trace-annotate \"FTP stops\""
proc finish {} {
global ns nf
$ns flush-trace
close $nf
puts "filtering..."
#exec tclsh../bin/namfilter.tcl goback.nam
#puts "running nam..."
exec nam goback.nam &
exit 0
}
$ns run.
OUTPUT
RESULT:
Thus the Go back N and Selective Repeat protocols were Simulated and studied.
61
CARRIER SENSE MULTIPLE ACCESS
AIM:
All devices have equal access to use the network when it is clear. In other words, a station that wants
to communicate "listen" first on the media communication and awaits a "silence" of a preset time
(called the Distributed Inter Frame Space or DIFS). After this compulsory period, the station starts a
countdown for a random period considered. The maximum duration of this countdown is called the
collision window (Window Collision, CW). If no equipment speaks before the end of the countdown,
the station simply delivers its package.
However, if it is overtaken by another station, it stops immediately its countdown and waits for the
next silence. then continued his account countdown where it left off. This is summarized in Figure.
The waiting time random has the advantage of allowing a statistically equitable distribution of
speaking time between the various network equipment, while making little unlikely (but not
impossible) that both devices speak exactly the same time.
The countdown system prevents a station waiting too long before issuing its package. It's a bit what
place in a meeting room when no master session (and all the World's polite) expected a silence, then
a few moments before speaking, to allow time for someone else to speak. The time is and randomly
assigned, that is to say, more or less equally.
ALGORITHM:
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 write mode.
62
5. Open the trace file and the win file in the write mode.
6. Transfer the packets in network.
7. Create the 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 tcp connection for source node.
11. Set the destination node using tcp sink.
12. Set the window size and the packet size for the tcp.
13. Set up the ftp over the tcp connection.
14. Set the udp and tcp connection for the source and destination.
15. Create the traffic generator CBR for the source and destination files.
16. Define the plot window and finish procedure.
17. In the definition of the finish procedure declare the global variables.
18. Close the trace file and namefile and execute the network animation file.
19. At the particular time call the finish procedure.
20. Stop the program.
PROGRAM:
set ns [new Simulator]
$ns color 1 blue
$ns color 2 red
set fi1 [open out.tr w]
set winfile [open WinFile w]
$ns trace-all $fi1
set fi2 [open out.nam w]
$ns namtrace-all $fi2
proc finish {}
{
global ns fi1 fi2
63
$ns flush-trace
close $fi1
close $fi2
exec nam out.nam &
exit 0
}
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
$n1 color red
$n1 shape box
$ns duplex-link $n0 $n2 2Mb 10ms DropTail
$ns duplex-link $n1 $n2 2Mb 10ms DropTail
$ns simplex-link $n2 $n3 0.3Mb 100ms DropTail
$ns simplex-link $n3 $n2 0.3Mb 100ms DropTail
set lan [$ns newLan "$n3 $n4 $n5" 0.5Mb 40ms LL Queue/DropTail MAC/Csma/Cd Channel]
set tcp [new Agent/TCP/Newreno]
$ns attach-agent $n0 $tcp
set sink [new Agent/TCPSink/DelAck]
$ns attach-agent $n4 $sink
$ns connect $tcp $sink
$tcp set fid_ 1
$tcp set window_ 8000
$tcp set packetsize_ 552
set ftp [new Application/FTP]
$ftp attach-agent $tcp
64
$ftp set type_ FTP
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
set cbr [new Application/Traffic/CBR]
$cbr attach-agent $udp
$cbr set type_ CBR
$cbr set packet_size_ 1000
$cbr set rate_ 0.01mb
$cbr set random_ false
$ns at 0.1 "$cbr start"
$ns at 1.0 "$ftp start"
$ns at 24.0 "$ftp stop"
$ns at 24.5 "$cbr stop"
proc plotwindow { tcpSource file }
{
global ns
set time 0.1
set now [$ns now]
set cwnd [$tcpSource set cwnd_]
set wnd [$tcpSource set window_]
puts $file "$now $cwnd"
$ns at [expr $now+$time] "plotwindow $tcpSource $file"
}
$ns at 1.0 "plotwindow $tcp $winfile"
$ns at 5 "$ns trace-annotate \"packet drop\""
65
$ns at 125.0 "finish"
$ns run
OUTPUT
RESULT
Thus the carrier sense multiple access are implemented and executed successfully.
66