CNLAB
CNLAB
(Regulations 2021)
SEMESTER V
(ACADEMIC YEAR 2024-25)
REGISTER NUMBER
1
SSM COLLEGE OF ENGINEERING
KOMARAPALAYAM- 638 183.
3
Simulation of error correction code (like
10 15-11-2024 CRC). 66
EX.N0:1 Learn to use commands like tcpdump, netstat, ifconfig, nslookup and
DATE: 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:
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
4
Commands:
Tcpdump;
Display traffic between 2 hosts:
To display all traffic between two hosts (represented by variables hostl and host2):
# tcpdump host hostl and host2
Display traffic from a source or destination host only:
To display traffic from only a source (src) or destination (dst) host:
# tcpdump src host
# tcpdump dst 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 tcp traffic :
# tcpdump tcp
Filtering based on source or destination port
To filter based on a source or destination port:
# tcpdump src
port ftp
# 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
5
ii C:\Wi11dow.s\system32\cmd.exe
3 ipconfig
In Windows, ipconfig is a console application designed to run from the Windows command
prompt. Th J.is utility allows you to get the IP address information of a Windows computer.
Using ipconfigFrom 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
6
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 TTLvalue 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
7
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 networkwith
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
# pingl 72.16.6.2
:ii C:\Windows\s.ystem32\cmd.exe
RESULT;
Thus the various networks commands like tcpdump, netstat, ifconfig, nslookup and traceroute ping are
executed successfully
8
EX.N0:2 Write a HTTP web client program to download a web page using
DATE: TCP sockets
AIM:
To write a java program for socket for HTTP for web page upload and download .
HTTP means HyperText Transfer Protocol. HTTP is the underlying protocol used by the
World Wide Web and this protocol defines how messages are formatted and transmitted,
and what actions Web servers and browsers should take in response to various commands.
For example, when you enter a URL in your browser, this actually sends an HTTP
command to the Web server directing it to fetch and transmit the requested Web page.
The other main standard that controls how the World Wide Web works is HTML, which
covers how Web pages are formatted and displayed. HTTP functions asa request response
protocol in the client-server computing model.
A web browser, for example, may be the client and an application running on a computer
hosting a website may be the server.
The client submits an HTTP request message to the server. The server, which provides
resources such as HTML files and other content, or performs other functions on behalf of
the client, returns a responsemessage to the client.
The response contains completion status information about the request and may also
contain requested content in its message body.
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
9
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
import java.net.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.swing.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import java.io.*:
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. ");
baos.flush();
img ImageIO.read(new File("digital_image_processing.jpg"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img, "jpg", baos);
DataOutputStream dos = new DataOutputStream(out);
dos.writeInt(bytes.length);
byte[] bytes = baos.toByteArray();
baos.close();
System.out.println("Sending image to server.");
OutputStream out = soc.getOutputStream();
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();
10
soc.close();
}
}
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 lendis.readInt();
System.out.println("Image Size: " + len/1024 + "KB");
byte[] data = new byte[len];
dis.readFully(data);
disclose();
in.close();
InputStream ian = new ByteArrayInputStream(data);
BufferedImage bImage ImageIO.read(ian);
JFrame f = new JFrame("Server");
ImageIcon icon = new ImageIcon(bImage);
JLabel 1= new JLabel();
L.setIcon(icon);
f.add(1);
f.pack();
f.setVisible(true);
}
11
OUTPUT:
When you run the client code, following output screen would appear on client side
RESULT:
Thus the socket program for HTTP for web page upload and download was
developed and executed successfully
12
EX.NO:3 Applications using TCP sockets like: Echo client and echo server,
DATE: Chat and File Transfer
AIM:
In the TCP Echo client a socket is created. Using the socket a connection is made to the
server using the connect() function. After a connection is established, we send messages
input from the user and display the data received from the server using send() and read()
functions.
In the TCP Echo server, we create a socket and bind to a advertized port number. After
binding the process listens for incoming connections. Then an infinite loop is started to
process the client requests for connections. After a connection is requested, it accepts the
connection from the client machine and forks a new process.
The new process receives data from the lient using recv() function and echoes the same data
using the send() function. Please note hat this server is capable of handling multiple clients
as it forks a new process for every client trying to connect to the server. TCP socket routines
enable reliable IP communication using the transmission control protocol (TCP).
A TCP connection must be established before exchanging data. TCP retransmits data that do
not reach the final destination due to errors or data corruption. Data is delivered in the
sequence of its transmission
13
a.Echo client and echo server
ALGORITHM
Client
1. Start
9. Stop
Server
1. Start
3. Accept the connection request sent by the client for connection establishment
7. Close the connection when client initiates termination and server becomes a listening server,
waiting for clients.
8. Stop.
14
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.println(line);
}
catch(IOException e)
{
System.out.println(e);
}
}
}
EClient.java
import java.net.*;
import java.io.*:
public class EClient
15
{
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 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());
}
catch(IOException e)
System.out.println("Socket Closed!");
}
16
OUTPUT:
Server
C:\Program Files\Java\jdk1.5.0\bin>
Client
Server:Hai Server
Client: Hello
Server:Hello
Client:end
Server:end
Client:ds
Socket Closed!
17
B.Chat
ALGORITHM
Client
1. Start
10. Stop
Server
1. Start
18
9. Repeat the steps from 3 to 8.
10. Stop.
PROGRAM
UDPserver.java
import java.io.*;
import java.net.*;
class UDPserver
public static DatagramSocket ds;
public static byte buffer[]=new byte[1024];
pulic static int clientport=789,serverport=790;
public static void main(String args[]) throws Exception
{
ds=new DatagramSocket(clientport);
BufferedReader dis=new BufferedReader(new InputStreamReader(System.in));
{
System.out.println("press ctrl+c to quit the program");
InetAddress ia InetAddress.geyLocalHost();
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
import java.io.*;
import java.net.*;
class UDPclient
{
public static DatagramSocket ds;
public static int clientport=789, serverport=790;
public static void main(String args[]) throws Exception
byte buffer[]=new byte[1024]; ds=new DatagramSocket(serverport);
BufferedReader dis-new BufferedReader(new InputStreamReader(System.in));
19
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);
String psx=new String(p.getData(),0,p.getLength());
ds.receive(p);
System.out.println("Server:" + psx);
}
20
OUTPUT:
Server
Client:Hai Server
Server:I am Fine
Client
C:\Program Files\Java\jdk1.5.0\bin>javac UDPclient.java
server waiting
Client:Hai Server
Server: I am Fine
Client:end
21
C. File Transfer
AIM:
Algorithm
Server
6. If file is exists then FileReader read the content until EOF is reached.
Client
4. The object of a BufferReader class is used for storing data content which has been retrieved from
socket object.
22
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
ServerSocket ssock = 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");
FileInputStream fis = new FileInputStream(file);
23
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. FileOutputStream fos = new
FileOutputStream("e:\\Bookmarks1.html");
BufferedOutputStream bos = new BufferedOutputStream(fos);
InputStream is = socket.getInputStream();
//No of bytes read in one read() call
int bytesRead = 0;
while((bytesRead is.read(contents))!=-1)
bos.write(contents, 0, bytesRead);
bos.flush();
socket.close():
System.out.println("File saved successfully!");
}
24
Output:
server
E:\nwlab>java FileServer
Sending file... 9% complete!
Sending file... 19% complete!
Sending file... 28% complete!
Sending file... 38% complete!
Sending file... 47% complete!
Sending file... 57% complete!
Sending file... 66% complete!
Sending file... 76% complete!
Sending file... 86% complete!
Sending file... 95% complete!
Sending file... 100% complete!
RESULT:
Thus the java application program using TCP Sockets was developed and executed successfully.
25
EX.NO:4
DATE: Simulation of DNS using UDP Sockets
AIM:
The Domain Name System (DNS) is a hierarchical decentralized naming system for
computers, services, or other resources connected to the Internet or a private network. It
associates various information with domain names assigned to each of the participating
entities.
The domain name space refers a hierarchy in the internet naming structure. This hierarchy
has multiple levels (from 0 to 127), with a root at the top. The following diagram shows the
domain name space hierarchy.
Name server contains the DNS database. This database comprises of various names and
their corresponding IP addresses. Since it is not possible for a single server to maintain
entire DNS database, therefore, the information is distributed among many DNS servers.
Root Server is the top level server which consists of the entire DNS tree. It does not contain
the information about domains but delegates the authority to the other server
Primary Server stores a file about its zone. It has authority to create, maintain, and update
the zone file.
Secondary Server transfers complete information about a zone from another server which
may be primary or secondary server. The secondary server does not have authority to create
or update a zone file.
DNS is a TCP/IP protocol used on different platforms. The domain name space is divided
into three different sections: generic domains, country domains, and inverse domain.
The main function of DNS is to translate domain names into IP Addresses, which computers
can understand. It also provides a list of mail servers which accept Emails for each domain
name. Each domain name in DNS will nominate a set of name servers to be authoritative for
its DNS records.
ALGORITHM:
26
Server
1. Start
6. Get the IP address mapped for the host name from the table.
8. Send the IP address for the requested host name to the client
9. Stop.
Client
1. Start
6. Receive the reply datagram and read the IP address for the requested host name
8. Stop.
PROGRAM
27
DNS Server
}
}
}
28
java import java.io.*;
import java.net.*;
public class udpdnsclient
OUTPUT:
29
Server
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
Ex.No:5
30
Date: Write a code simulating ARP /RARP protocols
AIM:
To write a java program for simulating ARP and RARP protocols using TCP.
Address Resolution Protocol (ARP) is a low-level network protocol for translating network
layer addresses into link layer addresses. ARP lies between layers 2 and 3 of the OSI model,
although ARP was not included in the OSI framework and allows computers to introduce
each other across a network prior to communication. Because protocols are basic network
communication units, address resolution is dependent on protocols such as ARP, which is
the only reliable method of handling required tasks.
The Address Resolution Protocol (ARP) is a communication protocol used for discovering
the link layer address, such as a MAC address, associated with a given internet layer
address,
When configuring a new network computer, each system is assigned an Internet Protocol
(IP) address for primary identification and communication. A computer also has a unique
media access control (MAC) address identity. Manufacturers embed the MAC address in the
local area network (LAN) card. The MAC address is also known as the computer's physical
address.
Address Resolution Protocol (ARP) is used to resolve an IPv4 address (32 bit Logical
Address) to the physical address (48 bit MAC Address). Network Applications at the
Application Layer use IPv4 Address to communicate with another device.
Reverse Address Resolution Protocol (RARP) is a network protocol used to resolve a data
link layer address to the corresponding network layer address. For example, RARP is used
to resolve a Ethernet MAC address to an IP address.
The client broadcasts a RARP packet with an ethernet broadcast address, and it's own
physical address in the data portion. The server responds by telling the client it's IP address.
Note there is no name sent. Also note there is no security.
Media Access Control (MAC) addresses need to be individually configured on the servers
by an administrator. RARP is limited to serving only IP addresses. Reverse ARP differs
from the Inverse Address Resolution Protocol which is designed to obtain the IP address
associated with a local Frame Relay data link connection identifier.
ALGORITHM:
31
Client
3. Get the IP address to be converted into MAC address from the user.
5. Receive the MAC address for the IP address from the server.
Server
2. Create the socket, bind the socket created with IP address and port number and make it a
listening socket..
4. Server maintains the table in which IP and corresponding MAC addresses are stored.
6. Retrieve the corresponding MAC address for the IP address and send it to the client.
7. Close the connection with the client and now the server becomes a listening server waiting for
the connection request from other clients
8. Stop
PROGRAM
32
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(strl+'\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{
ServerSocket obj=newServerSocket(139);
Socketobj1=obj.accept();
while(true)
{
DataInputStream din=new DataInputStream(objl.getInputStream());
DataOutputStream dout=new DataOutputStream(obj1.getOutputStream());
33
String str-din.readLine();
String mac[]={"6A:08:AA:C2","8A:BC:E3:FA"};
String ip[]=("165.165.80.80","165.165.79.1"); {
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:
34
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
(b) Program for Reverse Address Resolution Protocol (RARP) using UDP
35
ALGORITHM;
Client
3. Get the MAC address to be converted into IP address from the user.
5. Receive the datagram from the server and display the corresponding IP address.
6. Stop
Server
2. Server maintains the table in which IP and corresponding MAC addresses are stored.
4. Receive the datagram sent by the client and read the MAC address sent.
5. Retrieve the IP address for the received MAC address from the table.
7. Stop
PROGRAM:
36
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];
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);
37
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();
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:
38
I:\ex>java Serverrarp 12
1:\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.
39
Date: Control
Algorithms using NS
AIM:
To Study Network simulator (NS). and Simulation of Congestion Control Algorithms using
NS
Ns Overview
Ns Status
Periodical release (ns-2.26, Feb 2003)
Platform support
FreeBSD, Linux, Solaris, Windows and Mac
Ns functionalities
Routing. Transportation, Traffic sources, Queuing disciplines, QoS
Congestion Control Algorithms
Slow start
Additive increase/multiplicative decrease
Fast retransmit and Fast recovery
Case Study: A simple Wireless network.
Ad hoc routing, mobile IP, sensor-MAC
Tracing, visualization and various utilitie
NS(Network Simulators)
Most of the commercial simulators are GUI driven, while some network simulators are CLI driven.
The network model/configuration describes the state of the network (nodes, routers, switches, links)
and the events (data transmissions, packet error etc.). An important output of simulations are the
trace files. Trace files log every packet, every event that occurred in the simulation and are used for
analysis. Network simulators can also provide other tools to facilitate visual analysis of trends and
potential trouble spots.
Most network simulators use discrete event simulation, in which a list of pending "events" is stored,
and those events are processed in order, with some events triggering future events such as the event
of the arrival of a packet at one node triggering the event of the arrival of that packet at a
downstream node.
Simulation of networks is a very complex task. For example, if congestion is high, then estimation
of the average occupancy is challenging because of high variance. To estimate the likelihood of a
40
buffer overflow in a network, the time required for an accurate answer can be extremely large.
Specialized techniques such as "control variates" and "importance sampling" have been developed
to speed simulation.
Examples of network simulators
There are many both free/open-source and proprietary network simulators. Examples of notable
network simulation software are, ordered after how often they are mentioned in research papers:
1. ns (open source)
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 technologiesand can help the users to build
complex networks from basic building blocks such as a variety of nodes and links. With the help of
simulators, one can design hierarchical networks using various types of nodes like computers, hubs,
bridges, routers, switches, links, mobile units etc.
Various types of Wide Area Network (WAN) technologies like TCP, ATM, IP etc. and Local Area
Network (LAN) technologies like Ethernet, token rings etc., can all be simulated with a typical
simulator and the user can test, analyze various standard results apart from 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.
41
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
transportlayer 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 inbitsper second (bit/s orbps), and sometimes in data packets per second or data packets
per time slot. This measures how soon the receiver is able to get a certain amount ofdata send by the
sender. It is determined as the ratio of the total data received to the end to end delay. Throughput is
an important factor which directly impacts the network performance.
Delay
Delay is the time elapsed while a packet travels from one point e.g., source premise or network
ingress to destination premise or network degrees. The larger the value of delay, the more difficult
it is for transport layer protocols to maintain highbandwidths. 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. sender waits before retransmitting a lost segment.
42
Program:
include <wifi_lte/wifi_lte_rtable.h>
struct r_hist_entry *elm, *elm2;
int num_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_<
time){
}
STAILQ_REMOVE(&r_hist_elm2,r_hist_entry,linfo_); delete elm2; elm elm2; elm2
STAILQ_NEXT(elm, linfo_);
}
else
}
void DCCPTFRCAgent::removeAcksRecvHistory(){
struct r_hist_entry *elm1 = STAILQ_FIRST(&r_hist_);
struct r_hist_entry *elm2;
int num later = 1;
while (elm1 != NULL && num_later <= num_dup_acks_){
num_later;
elmi STAILQ_NEXT(elml, linfo_);
}
if(elml 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(elml, linfo_);
43
}
inline r_hist_entry
*DCCPTFRCAgent::findDataPacketInRecvHistory(r_hist_entry *start) {
while(start != NULL && start->type_DCCP_ACK)
start = STAILQ_NEXT(start,linfo_);
return start;
Result:
Thus we have Studied Network simulator (NS) and Simulation of Congestion Control
Algorithms using NS.
44
Ex.No: 7
Date: Study of TCP/UDP performance using Simulation tool.
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 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.
45
UDP is stateless,
UDP is suitable protocol for streaming applications such as VoIP, multimedia streaming.
TCP Performance
Algorithm
PROGRAM:
46
$ns duplex-link $n2 $n3 1.5Mb 10ms DropTail
$ns duplex-link-op Sn0 $n2 orient right-up
$ns duplex-link-op Sn1 $n2 orient right-down
Sns duplex-link-op $n2 $n3 orient right
Sns duplex-link-op Sn2 $n3 queuePos 0.5
set tep [new Agent/TCP]
Step set class_1
set sink [new Agent/TCPSink]
$ns attach-agent Sn1 Step
Sns attach-agent Sn3 $sink
Sns connect Step Ssink
set ftp [new Application/FTP]
Sftp attach-agent Step
$ns at 1.2 "$ftp start"
Sns at 1.35 "Sns detach-agent Sn1 Stcp; $ns detach-agent $n3 $sink"
Sns at 3.0 "finish"
proc finish () [
global ns f nf
Sns flush-trace
close Sf
close Snf
puts "Running nam.."
exec xgraph tepout.tr-geometry 600x800 &
exec nam tcpout.nam &
exit 0
Sns run
47
Output:
48
UDP Performance
ALGORITHM:
PROGRAM:
49
Sns attach-agent $no Sudp0
set cbr0 [new Application/Traffic/CBR]
Scbro attach-agent Sudp0
set udpl [new Agent/UDP]
Sns attach-agent Sn3 Sudpl
Sudpl set class_0
set cbr1 [new Application/Traffic/CBR]
Scbr1 attach-agent Sudpl
set null0 [new Agent/Null]
$ns attach-agent $n1 Snull0
set nulll [new Agent/Null]
Sns attach-agent $n1 $nulll
Sns connect Sudp0 $null)
Sns connect Sudp1 $null1.
$ns at 1.0 "Scbro start"
Sns at 1.1 "Scbr1 start"
puts [Scbr0 set packetSize
puts [Scbr0 set interval]
Sns at 3.0 "finish"
proc finish () [
global ns f nf
Sns flush-trace
close Sf
close Snf
puts "Running nam.."
exec nam udpout.nam &
exit 0
Sns run
50
Output:
RESULT:
51
Ex.No: 8
Date:
Simulation of Distance Vector/ Link State Routing algorithm.
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.
52
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.
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 fatallaw of
flooding. All nodes have neighbours and route packets indefinitely. More than two neighbours
creates a broadcast storm.
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 tothe sender.
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 nodes in a
network of topology changes, distance-vector routing protocols have less computational complexity
and message overhead.
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 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 destination.
Instead they use two methods:
53
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" isa.
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 toevery 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 delay and
available bandwidth.
Updates are performed periodically in a distance-vector protocol where all or part of a router's
routing table is sent to all its neighbors that are configured to use the same distance- vector 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 and inaccurate routing
information.
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 preference
value takes priority over the link cost.
Count-to-infinity problem
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 vector- update- 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 corrects itself, due to the
relaxation property of Bellman-Ford).
ALGORITHM:
54
4. Define the finish procedure.
PROGRAM
55
Scbro attach-agent Sudp0
set null() [new Agent/Null]
Sns attach-agent $n(3) Snull0
Sns connect Sudp0 Snullo
$ns at 0.5 "$cbr0 start"
$ns rtmodel-at 1.0 down Sn(1) Sn(2)
$ns rtmodel-at 2.0 up Sn(1) Sn(2)
$ns at 4.5 "$cbro stop"
Sns at 5.0 "finish"
Sns run
56
Output:
57
DISTANCE VECTOR ROUTING ALGORITHM
ALGORITHM:
3. Trace packets on all links onto NAM trace and text trace file
4. Define finish procedure to close files, flush tracing and run NAM
58
16. Stop
PROGRAM
59
# 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 Sn5 $n6 orient right-down
$ns duplex-link-op Sn6 $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 nl
set udp0 [new Agent/UDP]
$ns attach-agent Sn1 $udp0
#Create a CBR traffic source and attach it to udp0
set cbr0 [new Application/Traffic/CBR]
Scbro set packetSize_500
$cbro set interval 0.005
$cbro attach-agent $udp0
#Create a Null agent (a traffic sink) and attach it to node n4
set null0 [new Agent/Null]
$ns attach-agent Sn4 $null0
#Connect the traffic source with the traffic sink
$ns connect Sudp0 $nullo
#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"
Sns rtmodel-at 1.0 down $n3 Sn4
$ns rtmodel-at 2.0 up $n3 $n4
$ns at 4.5 "$cbro stop
#Call the finish procedure after 5 seconds of simulation time
$ns at 5.0 "finish"
#Run the simulation
$ns run
60
OUTPUT
$ ns distvect.tcl
61
62
RESULT:
Thus the simulation for Distance vector and link state routing protocols was done using NS2.
63
Ex.No:9 Use a tool like Wireshark to capture packets and examine the
Date: packets
AIM:
To write a Use a tool like Wireshark to capture packets and examine the packets.
We'll use the scapy library in Python to capture packets from a network interface.
The program will display basic information about each captured packet, such as source and
destination IP addresses, protocol, and packet summary.
The program will run indefinitely until the user decides to stop capturing packets.
ALGORITHM:
Create an infinite loop to capture packets continuously until the user stops the program.
PROGRAM:
import sys
from scapy.all import sniff, IP
def packet_handler(packet):
if IP in packet:
src_ip = packet[IP].src
dst_ip = packet[IP].dst
protocol = packet[IP].proto
packet_summary = packet.summary()
print(f"Source IP: (src_ip), Destination IP: (dst_ip), Protocol: (protocol), Summary:
[packet_summary)")
def main():
try:
print("Starting packet capture... (Press Ctrl+C to stop)")
64
sniff(prn-packet_handler, store=0)
except KeyboardInterrupt:
print("\nPacket capture stopped.")
if name ="main":
main()
Result:
65
Ex No:10
Date: Simulation of ErrorDetection Code (like CRC)
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:
66
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.
ALGORITHM:
2. Given a bit string, append OS to the end of it (the number of Os is the same as the degree of the
generator polynomial) let B(x) be the polynomial corresponding to B.
3. Divide B(x) by some agreed on polynomial G(x) (generator polynomial) and determine the
remainder R(x). This division is to be done using Modulo 2 Division.
7. Let T' represent the bit stream the receiver gets and T'(x) the associated polynomial. The receiver
divides T1(x) by G(x). If there is a 0 remainder, the receiver concludes T = T' 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 {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int[] data;
int[] div;
67
int[] divisor;
int[] rem;
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];
cre=new int[tot_length];
/*
CRC GENERATION
for(int i=0;i<data.length;i++)
div[i]=data[i];
System.out.print("Dividend (after appending O's) are: "); for(int i = 0 i< div.length; i++)
System.out.print(div[i]);
System.out.println();
for( 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();
68
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("cre 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(irem.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;
69
OUTPUT:
RESULT:
Thus the above program for error checking code using was executed successfully.
70