[go: up one dir, main page]

0% found this document useful (0 votes)
16 views48 pages

CN Lab

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 48

Exp No: 1

DATE: NETWORKING COMMANDS

AIM:
To study the basic networking commands.

NETWORKING COMMANDS:

C:\>arp –a: ARP is short form of address resolution protocol, It will show the IP address of your
computer along with the IP address and MAC address of your router.

C:\>hostname: This is the simplest of all TCP/IP commands. It simply displays the name of yourcomputer.

C:\>ipconfig: The ipconfig command displays information about the host (the computer yoursitting
at)computer TCP/IP configuration.

C:\>ipconfig /all: This command displays detailed configuration information about your TCP/IP
connection including Router, Gateway, DNS, DHCP, and type of Ethernet adapter inyour system.

C:\>Ipconfig /renew: Using this command will renew all your IP addresses that you are currently(leasing)
borrowing from the DHCP server. This command is a quick problem solver if you are having connection
issues, but does not work if you have been configured with a static IP address.

C:\>Ipconifg /release: This command allows you to drop the IP lease from the DHCPserver.

C:\>ipconfig /flushdns: This command is only needed if you‟re having trouble with your
networksDNS configuration. The best time to use this command is after network configuration
frustration sets in, and you really need the computer to reply with flushed.

C:\>nbtstat –a: This command helps solve problems with NetBIOS name resolution.
(Nbtstands for NetBIOS over TCP/IP)

C:\>netdiag: Netdiag is a network testing utility that performs a variety of network diagnostic tests,allowing
you to pinpoint problems in your network. Netdiag isn‟t installed by default, but can be installed from the
Windows XP CD after saying no to the install. Navigate to the CD ROM drive letter and open the support\
tools folder on the XP CD and click the setup.exe icon in the support\tools folder.

C:\>netstat: Netstat displays a variety of statistics about a computers active TCP/IP connections. This tool
is most useful when you‟re having trouble with TCP/IP applications such as HTTP, andFTP.

C:\>nslookup: Nslookup is used for diagnosing DNS problems. If you can access a
resource by specifying an IP address but not it‟s DNS you have a DNS problem.
C:\>pathping: Pathping is unique to Window‟s, and is basically a combination of the Ping and Tracert
commands. Pathping traces the route to the destination address then launches a 25 second test of each router
along the way, gathering statistics on the rate of data loss along each hop.

C:\>ping: Ping is the most basic TCP/IP command, and it‟s the same as placing a phone call to your best
friend. You pick up your telephone and dial a number, expecting your best friend to replywith “Hello” on
the other end. Computers make phone calls to each other over a network by usinga Ping command. The
Ping commands main purpose is to place a phone call to another computer onthe network, and request an
answer. Ping has 2 options it can use to place a phone call to another computer on the network. It can use
the computers name or IP address.

C:\>route: The route command displays the computers routing table. A typical computer, with a single
network interface, connected to a LAN, with a router is fairly simple and generally doesn‟tpose any
network problems. But if you‟re having trouble accessing other computers on your network, you can use
the route command to make sure the entries in the routing table are correct.

C:\>tracert: The tracert command displays a list of all the routers that a packet has to go through toget from
the computer where tracert is run to any other computer on the internet.

RESULT:

Thus the above list of primitive has been studied.


Exp No : 2 Write a HTTP web client program to download a web
DATE: page using TCP sockets

AIM:

To Write a HTTP web client program to download a web page using TCP sockets.

ALGORITHM:

CLIENT SIDE:

1) Start the program.


2) Create a socket which binds the Ip address of server and the port address to
acquire service.
3) After establishing connection send the url to server.
4) Open a file and store the received data into the file.
5) Close the socket.
6) End the program.

SERVER SIDE

1) Start the program.


2) Create a server socket to activate the port address.
3) Create a socket for the server socket which accepts the connection.
4) After establishing connection receive url from client.
5) Download the content of the url received and send the data to client.
6) Close the socket.
7) End the program.

PROGRAM
import javax.swing.*;
import java.net.*;
import
java.awt.image.*;import
javax.imageio.*; import
java.io.*;
import
java.awt.image.BufferedImage;
import
java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class HTTPClient
{
public static void main(String args[]) throws Exception

{
Socket soc;
BufferedImage img =
null;soc=new
Socket("localhost",4000)
;
System.out.println("Client is running.");try

{
System.out.println("Reading image from disk.");
img = ImageIO.read(new File("digital-image-processing.jpg"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img, "jpg", baos);
baos.flush();byte[] bytes = baos.toByteArray();
baos.close(); System.out.println("Sending image to
server."); OutputStream out =
soc.getOutputStream(); DataOutputStream dos =
new DataOutputStream(out);
dos.writeInt(bytes.length);
dos.write(bytes, 0, bytes.length);
System.out.println("Image sent to
server."); dos.close();
out.close();
}
catch (Exception e)
{
System.out.println("Exception: " +
e.getMessage()); soc.close();
}
soc.close();
}
}

SERVER PROGRAM

import
java.net.*;
import
java.io.*;
import
java.awt.image.*;
import
javax.imageio.*;
import javax.swing.*;
class HTTPServer
{
public static void main(String args[]) throws Exception
{
ServerSocket
server=null; Socket
socket;
server=new ServerSocket(4000);
System.out.println("Server Waiting for
image"); socket=server.accept();
System.out.println("Client connected.");
InputStream in = socket.getInputStream();
DataInputStream dis = new
DataInputStream(in);int len = dis.readInt();
System.out.println("Image Size: " + len/1024 + "KB");
byte[] data = new byte[len];
dis.readFully(data);
dis.close();
in.close();
InputStream ian = new ByteArrayInputStream(data);
BufferedImage bImage = ImageIO.read(ian); JFrame f =
new JFrame("Server");
ImageIcon icon = new
ImageIcon(bImage);
JLabel l = new JLabel();
l.setIcon(icon);
f.add(l);
f.pack();
f.setVisible(true);
}
}
RESULT:

The webpage is successfully downloaded and the contents are displayed and verified.
Exp No :3a SOCKET PROGRAM FOR ECHO
DATE:

Aim
To implement echo server and client in java using TCP sockets.

Algorithm :
Server
1. Create a server socket.
2. Wait for client to be connected.
3. Read text from the client
4. Echo the text back to the client.
5. Repeat steps 4-5 until „bye‟ or „null‟ is read.
6. Close the I/O streams
7. Close the server socket
8. Stop

Client
1. Create a socket and establish connection with the server
2. Get input from user.
3. If equal to bye or null, then go to step 7.
4. Send text to the server.
5. Display the text echoed by the server
6. Repeat steps 2-4
7. Close the I/O streams
8. Close the client socket
9. Stop

PROGRAM:

ECHO CLIENT
import
java.net.*;
import java.io.*;
public class
echoclient
{
public static void main(String[] args) throws IOException
{
BufferedReader fromServer = null, fromUser =
null; PrintWriter toServer = null;
Socket sock
= null;try {
if (args.length == 0)
sock = new Socket(InetAddress.getLocalHost(), 4000);
else
sock = new Socket(InetAddress.getByName(args[0]), 4000);
fromServer = new BufferedReader(new InputStreamReader(sock.getInputStream()));
fromUser = new BufferedReader(new InputStreamReader(System.in));
toServer = new PrintWriter(sock.getOutputStream(),
true String Usrmsg, Srvmsg;
System.out.println("Type \"bye\" to quit");
while (true)
{

System.out.print("Enter msg to server : ");


Usrmsg = fromUser.readLine();
if (Usrmsg==null || Usrmsg.equals("bye"))
{

toServer.println("bye")
;break;
}
else
toServer.println(Usrmsg)
;
Srvmsg = fromServer.readLine();
System.out.println(Srvmsg);
}
fromUser.close();
fromServer.close(
);toServer.close();
sock.close();
}
catch (IOException ioe)
{
System.err.println(ioe);
}
Echo Server:
import
java.net.*;
import java.io.*;
public class
echoserver
{
public static void main(String[] arg) throws IOException
{
ServerSocket sock = null;
BufferedReader fromClient = null;
OutputStreamWriter toClient = null;
Socket client = null;
try {
sock = new ServerSocket(4000);
System.out.println("Server Ready");
client = sock.accept();
System.out.println("Client Connected");
FromClient = new BufferedReader(new InputStreamReader(client.getInputStream()));
toClient = new OutputStreamWriter(client.getOutputStream());
String
line; while
(true)
{
line = fromClient.readLine();
if ( (line == null) || line.equals("bye"))
break;
System.out.println ("Client [ " + line + " ]");
toClient.write("Server [ "+ line +" ]\n");
toClient.flush();
}
fromClient.close();toClient.close(); client.close(); sock.close();
System.out.println("Client Disconnected");
}
catch (IOException ioe)
{
System.err.println(ioe);
}}}

RESULT:

Thus the program for simulation of echo server was written & executed.
Exp No:3b
DATE: CLIENT- SERVER APPLICATION FOR CHAT

Aim
To implement a chat server and client in java using TCP sockets.

Algorithm
Server
1. Create a server socket
2. Wait for client to be connected.
3. Read Client's message and display it
4. Get a message from user and send it to client
5. Repeat steps 3-4 until the client sends "end"
6. Close all streams
7. Close the server and client socket
8. Stop
Client
1. Create a client socket and establish connection with the server
2. Get a message from user and send it to server
3. Read server's response and display it
4. Repeat steps 2-3 until chat is terminated with "end" message
5. Close all input/output streams
6. Close the client socket
7. Stop

PROGRAM:
// TCP Chat Server--tcpchatserver.java
import
java.io.*;
import
java.net.*; class
tcpchatserver
{
public static void main(String args[])throws Exception
{
PrintWriter toClient;
BufferedReader fromUser,
fromClient;try
{
ServerSocket Srv = new
ServerSocket(5555);
System.out.print("\nServer started\n");
Socket Clt = Srv.accept();
System.out.println("Client
connected");
toClient = new PrintWriter(new BufferedWriter(new OutputStreamWriter(Clt.getOutputStream())),
true);fromClient = new BufferedReader(new InputStreamReader(Clt.getInputStream()));
fromUser = new BufferedReader(new
InputStreamReader(System.in));String CltMsg, SrvMsg;
while(true)
{
CltMsg=
fromClient.readLine();
if(CltMsg.equals("end"))
break
; else
{
System.out.println("\nServer <<< " +
CltMsg);System.out.print("Message to
Client : "); SrvMsg = fromUser.readLine();
toClient.println(SrvMsg);
}}
System.out.println("\nClient
Disconnected");fromClient.close();
toClient.close();

fromUser.clos
e();Clt.close()
;

Srv.close();
}
catch (Exception E)
{
System.out.println(E.getMessage());
}}}

// TCP Chat Client--tcpchatclient.java


import
java.io.*;
import
java.net.*;class
tcpchatclient
{
public static void main(String args[])throws Exception
{
Socket Clt; PrintWriter toServer;
BufferedReader fromUser,
fromServer;try {
if (args.length > 1)
{
System.out.println("Usage: java
hostipaddr");System.exit(-1); }
if (args.length == 0)
Clt = new
Socket(InetAddress.getLocalHost(),5555);else
Clt = new Socket(InetAddress.getByName(args[0]), 5555);
toServer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(Clt.getOutputStream())),
true);fromServer = new BufferedReader(new InputStreamReader(Clt.getInputStream()));
fromUser = new BufferedReader(new
InputStreamReader(System.in));String CltMsg, SrvMsg;
System.out.println("Type \"end\" to Quit");
while (true) { System.out.print("\nMessage to Server :
");CltMsg = fromUser.readLine();
toServer.println(CltMsg);
if
(CltMsg.equals("end"))
break; SrvMsg =
fromServer.readLine();
System.out.println("Client <<< " + SrvMsg);
}}
catch(Exception E) {
System.out.println(E.getMessage());
}}}

RESULT:
Thus the above program a client-server application for chat using TCP / IP was
executed and successfully.
Exp No: 4
DATE: Simulation of DNS using UDP sockets.

AIM:
To write a program to Simulation of DNS using UDP sockets..

ALGORITHM:

1. Start the program.


2. Get the frame size from the user
3. To create the frame based on the user
request.4.To send frames to server from
the client side.
5. If your frames reach the server it will send ACK signal to client otherwise
it willsend NACK signal to client.
6. Stop the program

PROGRAM:

/ UDP DNS
Server
Udpdnsserver
java import
java.io.*;import
java.net.*;
public class udpdnsserver
{
private static int indexOf(String[] array, String str)
{
str = str.trim();
for (int i=0; i < array.length; i++)
{
if (array[i].equals(str)) return i;
}
return -1;
}
public static void main(String arg[])throws IOException
{
String[] hosts = {"yahoo.com", "gmail.com","cricinfo.com", "facebook.com"}; String[]
ip = {"68.180.206.184", "209.85.148.19","80.168.92.140", "69.63.189.16"};
System.out.println("Press Ctrl + C to Quit");
while (true){
DatagramSocket serversocket=new DatagramSocket(1362);
byte[] senddata = new byte[1021];
byte[] receivedata = new byte[1021];
DatagramPacket recvpack = new DatagramPacket(receivedata,
receivedata.length); serversocket.receive(recvpack);
String sen = new String(recvpack.getData()); InetAddress ipaddress =
recvpack.getAddress(); int port = recvpack.getPort();
String capsent;
System.out.println("Request for host " + sen);
if(indexOf (hosts, sen) != -1) capsent = ip[indexOf
(hosts, sen)]; else capsent = "Host Not Found";

senddata = capsent.getBytes();
DatagramPacket pack = new DatagramPacket (senddata, senddata.length,ipaddress,port);
serversocket.send(pack);
serversocket.close();
}
}
}

//UDP DNS Client –


Udpdnsclient
.java import java.io.*; import
java.net.*; public class udpdnsclient
{
public static void main(String args[])throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientsocket = new DatagramSocket();
InetAddress ipaddress; if (args.length == 0)
ipaddress = InetAddress.getLocalHost();
else
ipaddress = InetAddress.getByName(args[0]); byte[] senddata =
new byte[1024];
byte[] receivedata = new
byte[1024]; int portaddr = 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);
DatagramPacket recvpack =new DatagramPacket(receivedata,receivedata.length);
clientsocket.receive(recvpack);
String modified = new
String(recvpack.getData());
System.out.println("IP Address: " + modified);
clientsocket.close();
}
}
RESULT:

Thus the above program a client-server application for chat using UDP was executed and
successfully.
Exp No: 5 Use a tool like Wireshark to capture packets and
DATE : examine the packets

AIM :

To Implement a tool like Wireshark to capture packets and examine the packets.

Algorithm:

Wireshark Packet Capture and Examination:

1. Initialization:

 Launch Wireshark application.

2. Select Network Interface:

 Prompt user to select the network interface(s) to capture packets from.


 Start capturing packets on the selected interface(s).

3. Optional: Apply Filters (if specified

 If the user specifies filter criteria, apply filters to capture packets based on the specified conditions
(e.g., IP addresses, protocols, ports).
 Begin capturing packets based on the applied filters.

4. Capture Packets:

 Continuously capture packets from the selected network interface(s).


 Store captured packets in a buffer for analysis.

5. Examine Packets:

 Display captured packets in the Wireshark interface.


 Provide detailed packet information, including source and destination IP addresses, ports,
protocols, packet payloads, etc.
 Allow users to select individual packets to view detailed packet contents.

6. Display Summary Statistics:

 Calculate and display summary statistics on captured packets, such as total packets captured,
packet rate, protocol distribution, etc.
 Update statistics in real-time as new packets are captured.

7. Stop Packet Capture:

 Provide an option to stop packet capture when desired.


 Release network interface(s) and stop capturing packets.

8. End Session:

 Close the Wireshark application.

Program :

import jpcap.*;
import
jpcap.packet.*;

public class PacketCaptureExample

{ public static void main(String[] args)

{
try {
// Obtain a list of network interfaces
NetworkInterface[] devices = JpcapCaptor.getDeviceList();

// Select a network interface for packet capture (e.g., devices[0])


int index = 0; // Change this index as needed
NetworkInterface device = devices[index];

// Open a Jpcap capture session on the selected network interface


int snapshotLength = 65536; // Maximum packet length to capture
int timeout = 50; // Packet capture timeout in milliseconds
int promiscuousMode = Jpcap.MODE_PROMISCUOUS; // Capture mode
JpcapCaptor captor = JpcapCaptor.openDevice(device, snapshotLength, false, timeout);

System.out.println("Starting packet capture...");

// Start capturing packets


while (true) {
// Capture a single packet
Packet packet = captor.getPacket();

// Check if the packet is null (no packets captured within timeout)


if (packet == null) {
continue;
}

// Print out packet details


System.out.println("Packet Captured:");
System.out.println(packet.toString());
}
} catch (Exception e)
{ e.printStackTrace(
);
}
}
Result :

Thus the Wireshark to capture packets and examine the packets has been implemented.
Exp No : 6a Write a code simulating ARP protocols.
DATE:

AIM
To implement Address Resolution Protocol .

ALGORITH

M CLIENT

SIDE

 Establish a connection between the Client and Server.


Socket ss=new Socket(Inet Address. get Local
Host(),1100);
 Create instance output stream writer
 Print Writer ps=new PrintWriter(s. get Output Stream(),true);
 Get the IP Address to resolve its physical address.
 Send the IPAddress to its output Stream.ps.println(ip);
 Print the Physical Address received from the server.

SERVER SIDE

 Accept the connection request by the client.


 Server Socket ss=new Server Socket(2000);Socket s=ss.accept();
 Get the IP address from its input stream.
 Buffered Reader br1=new Buffered Reader(new Input Stream
Reader (s.getInputStream()));ip=br1.readLine();
 During runtime execute the process Runtime
r=Runtime.get Runtime();Process p=r.exec("arp -a "+ip);
 Send the Physical Address to the client.

PROGRAM
CLIENT

import java.io.*;
import java.net.*;

class ArpClient
{
public static void main(String args[])throws IOException
{
try
{
Socket ss=new Socket(InetAddress.getLocalHost(),1100);
PrintStream ps=new PrintStream(ss.getOutputStream())
BufferedReader br=new BufferedReader(newInputStreamReader(System.in));String ip;
System.out.println("Enter the IPADDRESS:");

ip=br.readLine();
ps.println(ip);
String str,data;
BufferedReader
br2=new
BufferedReader(newInputStreamReader(ss.getInputStream()));
System.out.println("ARP From Server::"); do
{
str=br2.readLine();
System.out.println(str);
}
while(!(str.equalsIgnoreCase("end")));
}
catch(IOException e)
{
System.out.println("Error"+e);

}}}

ARP SERVER

import java.io.*; import


java.net.*;

class ArpServer
{
public static void main(String args[])throws IOException
{
try
{
ServerSocket ss=new ServerSocket(1100);
Socket s=ss.accept();
PrintStream ps=new PrintStream(s.getOutputStream());
BufferedReader br1=new BufferedReader(newInputStreamReader(s.getInputStream()));String ip;
ip=br1.readLine();
Runtime
r=Runtime.getRuntime(); Process
p=r.exec("arp -a "+ip);
BufferedReader br2=new
BufferedReader(newInputStreamReader(p.getInputStream()));String str;
while((str=br2.readLine())!=null)
{
ps.println(str);
}}
catch(IOException e)
{
System.out.println("Error"+e); }}}
RESULT
Thus the implementation of ARP is done & executed successfully.
Exp No : 6b Write a code simulating RARP protocols.
DATE

AIM:
To write a java program for simulating RARP protocols.
ALGORITHM:

CLIENT
1. Start the program
2. using datagram sockets UDP function is established.
2. Get the MAC address to be converted into IP address.
3. Send this MAC address to server.
4. Server returns the IP address to client.

SERVER
1. Start the program.
2. Server maintains the table in which IP and corresponding MAC addresses are stored.
3. Read the MAC address which is send by the client.
4. Map the IP address with its MAC address and return the IP address to client.

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);
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=newDatagramPacket(sendbyte,sendbyte.length,addr,port);
server.send(sender);
break;
}

}
break;
}
}
catch(Exception e)
{
System.out.println(e);

}
}
}

RESULT:

Thus the implementation of RARP is done & executed successfully.


Exp No : 7 Study of Network simulator (NS) and Simulation of Congestion
DATE: Control Algorithms using NS

AIM:
To Study Network simulator (NS).and Simulation of Congestion Control Algorithms
using NS

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;
} else
elm = elm2;
elm2 = STAILQ_NEXT(elm, linfo_);
}
}
}
}
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;
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;
}
Result:
Thus we have Studied Network simulator (NS) and Simulation of Congestion Control
Algorithms using NS.
Ex.No: 8
DATE: Study of TCP/UDP performance using Simulation tool.

AIM:

To simulate the performance of TCP/UDP using NS2.

TCP Performance
Algorithm
1. Create a Simulator object.
2. Set routing as dynamic.
3. Open the trace and nam trace files.
4. Define the finish procedure.
5. Create nodes and the links between them.
6. Create the agents and attach them to the nodes.
7. Create the applications and attach them to the tcp agent.
8. Connect tcp and tcp sink.
9. Run the simulation.
PROGRAM:
$ns [new Simulator]
$ns color 0 Blue
$ns color 1 Red
$ns color 2 Yellow
t n0 [$ns node]
t n1 [$ns node]
t n2 [$ns node]
t n3 [$ns node]
t f [open tcpout.tr w]
$ns trace-all $f
t nf [open tcpout.nam w]
$ns namtrace-all $nf
$ns duplex-link $n0 $n2 5Mb 2ms DropTail
$ns duplex-link $n1 $n2 5Mb 2ms DropTail
$ns duplex-link $n2 $n3 1.5Mb 10ms DropTail
$ns duplex-link-op $n0 $n2 orient right-up
$ns duplex-link-op $n1 $n2 orient right-down
$ns duplex-link-op $n2 $n3 orient right
$ns duplex-link-op $n2 $n3 queuePos 0.5
t tcp [new Agent/TCP]
cp set class_ 1
t sink [new Agent/TCPSink]
$ns attach-agent $n1 $tcp
$ns attach-agent $n3 $sink
$ns connect $tcp $sink
t ftp [new Application/FTP]
tp 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"
oc finish {} {
global ns f nf

$ns flush-trace
close $f
close $nf
puts "Running nam.."
exec xgraph tcpout.tr -geometry 600x800 &
exec nam tcpout.nam &
exit 0
}
$ns run
UDP Performance

ALGORITHM :

1. Create a Simulator object.

2. Set routing as dynamic.

3. Open the trace and nam trace files.

4. Define the finish procedure.

5. Create nodes and the links between them.

6. Create the agents and attach them to the nodes.

7. Create the applications and attach them to the UDP agent.

8. Connect udp and null agents.

9. Run the simulation.

PROGRAM:
set ns [new Simulator]
$ns color 0 Blue
$ns color 1 Red
$ns color 2 Yellow
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set f [open udpout.tr w]
$ns trace-all $f
set nf [open udpout.nam w]
$ns namtrace-all $nf
$ns duplex-link $n0 $n2 5Mb 2ms DropTail
$ns duplex-link $n1 $n2 5Mb 2ms DropTail
$ns duplex-link $n2 $n3 1.5Mb 10ms DropTail
$ns duplex-link-op $n0 $n2 orient right-up
$ns duplex-link-op $n1 $n2 orient right-down
$ns duplex-link-op $n2 $n3 orient right
$ns duplex-link-op $n2 $n3 queuePos 0.5
set udp0 [new Agent/UDP]
$ns attach-agent $n0 $udp0
set cbr0 [new Application/Traffic/CBR]
$cbr0 attach-agent $udp0
set udp1 [new Agent/UDP]
$ns attach-agent $n3 $udp1
$udp1 set class_ 0
set cbr1 [new Application/Traffic/CBR]
$cbr1 attach-agent $udp1
set null0 [new Agent/Null]
$ns attach-agent $n1 $null0
set null1 [new Agent/Null]
$ns attach-agent $n1 $null1
$ns connect $udp0 $null0
$ns connect $udp1 $null1
$ns at 1.0 "$cbr0 start"

$ns at 1.1 "$cbr1 start"


puts [$cbr0 set packetSize_]
puts [$cbr0 set interval_]
$ns at 3.0 "finish"
proc finish {} {
global ns f nf
$ns flush-trace
close $f
close $nf
puts "Running nam.."
exec nam udpout.nam &
exit 0
}
$ns run
RESULT :

Thus the study of TCP/UDP performance is done successfully.


Ex.No: 9
DATE: Simulation of Distance Vector/ Link State Routing algorithm.

AIM:

To simulate the Distance vector and link state routing protocols using NS2.

ALGORITHM:
1. Create a Simulator object.
2. Set routing as dynamic.
3. Open the trace and nam trace files.
4. Define the finish procedure.
5. Create nodes and the links between them.
6. Create the agents and attach them to the nodes.
7. Create the applications and attach them to the udp agent.
8. Connect udp and null..
9. At 1 sec the link between node 1 and 2 is broken.
10. At 2 sec the link is up again.
11. Run the simulation.

LINK STATE ROUTING PROTOCOL


PROGRAM
set ns [new Simulator]
$ns rtproto LS
set nf [open linkstate.nam w]
$ns namtrace-all $nf
set f0 [open linkstate.tr w]
$ns trace-all $f0
proc finish {} {
global ns f0 nf
$ns flush-trace
close $f0
close $nf
exec nam linkstate.nam &
exit 0
}
for {set i 0} {$i <7} {incr i} {
set n($i) [$ns node]
}
for {set i 0} {$i <7} {incr i} {
$ns duplex-link $n($i) $n([expr ($i+1)%7]) 1Mb 10ms DropTail
}
set udp0 [new Agent/UDP]
$ns attach-agent $n(0) $udp0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0
set null0 [new Agent/Null]
$ns attach-agent $n(3) $null0
$ns connect $udp0 $null0
$ns at 0.5 "$cbr0 start"
$ns rtmodel-at 1.0 down $n(1) $n(2)
$ns rtmodel-at 2.0 up $n(1) $n(2)
$ns at 4.5 "$cbr0 stop"

$ns at 5.0 "finish"


$ns run
DISTANCE VECTOR ROUTING ALGORITHM

ALGORITHM:
1. Create a simulator object
2. Set routing protocol to Distance Vector routing
3. Trace packets on all links onto NAM trace and text trace file
4. Define finish procedure to close files, flush tracing and run NAM
5. Create eight nodes
6. Specify the link characteristics between nodes
7. Describe their layout topology as a octagon
8. Add UDP agent for node n1
9. Create CBR traffic on top of UDP and set traffic parameters.
10. Add a sink agent to node n4
11. Connect source and the sink
12. Schedule events as follows:
a. Start traffic flow at 0.5
b. Down the link n3-n4 at 1.0
c. Up the link n3-n4 at 2.0
d. Stop traffic at 3.0
e. Call finish procedure at 5.0
13. Start the scheduler
14. Observe the traffic route when link is up and down
15. View the simulated events and trace file analyze it
16. Stop

PROGRAM
#Distance vector routing protocol – distvect.tcl
#Create a simulator object
set ns [new Simulator]
#Use distance vector routing
$ns rtproto DV
#Open the nam trace file
set nf [open out.nam w]
$ns namtrace-all $nf
# Open tracefile
set nt [open trace.tr w]
$ns trace-all $nt
#Define 'finish' procedure
proc finish {}
{
global ns nf
$ns flush-trace
#Close the trace file
close $nf
#Execute nam on the trace file
exec nam -a out.nam &
exit 0
}
# Create 8 nodes
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
set n6 [$ns node]
set n7 [$ns node]
set n8 [$ns node]
# Specify link characterestics
$ns duplex-link $n1 $n2 1Mb 10ms DropTail
$ns duplex-link $n2 $n3 1Mb 10ms DropTail

$ns duplex-link $n3 $n4 1Mb 10ms DropTail


$ns duplex-link $n4 $n5 1Mb 10ms DropTail
$ns duplex-link $n5 $n6 1Mb 10ms DropTail
$ns duplex-link $n6 $n7 1Mb 10ms DropTail
$ns duplex-link $n7 $n8 1Mb 10ms DropTail
$ns duplex-link $n8 $n1 1Mb 10ms DropTail
# specify layout as a octagon
$ns duplex-link-op $n1 $n2 orient left-up
$ns duplex-link-op $n2 $n3 orient up
$ns duplex-link-op $n3 $n4 orient right-up
$ns duplex-link-op $n4 $n5 orient right
$ns duplex-link-op $n5 $n6 orient right-down
$ns duplex-link-op $n6 $n7 orient down
$ns duplex-link-op $n7 $n8 orient left-down
$ns duplex-link-op $n8 $n1 orient left
#Create a UDP agent and attach it to node n1
set udp0 [new Agent/UDP]
$ns attach-agent $n1 $udp0
#Create a CBR traffic source and attach it to udp0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0
#Create a Null agent (a traffic sink) and attach it to node n4
set null0 [new Agent/Null]
$ns attach-agent $n4 $null0
#Connect the traffic source with the traffic sink
$ns connect $udp0 $null0
#Schedule events for the CBR agent and the network dynamics
$ns at 0.0 "$n1 label Source"
$ns at 0.0 "$n4 label Destination"
$ns at 0.5 "$cbr0 start"
$ns rtmodel-at 1.0 down $n3 $n4
$ns rtmodel-at 2.0 up $n3 $n4
$ns at 4.5 "$cbr0 stop"
#Call the finish procedure after 5 seconds of simulation time

$ns at 5.0 "finish"


$ns run
RESULT:

Thus the simulation for Distance vector and link state routing protocols was done using NS2.
Exp No : 10
DATE: Simulation of error correction code (like CRC)

AIM:

To implement and check the error detection/error correction techniques in networks using a c program.

Error Detection

• Bit errors occur in frames due to electrical interference or thermal noise.


• Detecting errors is one part of the problem; correcting errors is the other.
• What happens when an error is detected?
• Two basic approaches:
– Notify the sender that message is corrupt so the sender can retransmit it; ( most
often used in every day applications)
– Use an error-correcting code to reconstruct the correct message
Transmission Errors

· External electromagnetic signals can cause incorrect delivery of data

- · Data can be received incorrectly


- · Data can be lost
- · Unwanted data can be generated
· Any of these problems are called transmission errors

Error Detection

• Detecting Transmission Errors: basic idea is to add redundant information to a frame that
can determine if errors have been introduced.
Error Correction or Error Detection?

• When error is detected, frame is discarded and resent, using bandwidth and causing
latency, waiting for its arrival.
• Error correction requires additional bit to be sent with every frame.
• Correction is useful when
• 1) errors are probable or
• 2) the cost of retransmission is too high
Cyclic Redundancy Check (CRC)

CRC is a different approach to detect if the received frame contains valid data. This
techniqueinvolves binary division of the data bits being sent. The divisor is generated using
polynomials. The sender performs a division operation on the bits being sent and calculates the
remainder. Before sending the actual bits, the sender adds the remainder at the end of theactual bits.
Actual data bits plus the remainder is called a codeword. The sender transmits databits as code
words.
At the other end, the receiver performs division operation on codewords using the same CRC divisor. If the
remainder contains all zeros the data bits are accepted, otherwise it is consideredas there some data
corruption occurred in transit.

PROCEDURE:

 Start the process.


 Give the data which is the message.
 Compile and run the program.
 Enter the received hamming code.
 The error is corrected codeword.

PROGRAM FOR CODE GENERATION FOR ERROR DETECTION AND CORRECTION

import java.util.Scanner;
class CRC
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int m,g[],n,d[],z[],r[],msb,i,j,k;

System.out.print("ENTER NUMBER OF DATA BITS:\


n"); n=sc.nextInt();
System.out.print("ENTER NUMBER OF GENERATOR BITS:\n");
m=sc.nextInt();
d=new int[n+m];
g=new int[m];
System.out.print("ENTER DATA BITS:\n");
for(i=0;i<n;i++)
d[i]=sc.nextInt();
System.out.print("ENTER GENERATOR BITS:\n");

for(j=0;j<m;j++)
g[j]=sc.nextInt();

for(i=0;i<m-1;i++)
d[n+i]=0;
r=new int[m+n];

for(i=0;i<m;i++)
r[i]=d[i];
z=new int[m];

for(i=0;i<m;i++)
z[i]=0;

for(i=0;i<n;i++)
{ k=
0;
msb=r[i]; for(j=i;j<m+i;j+
+)
{
if(msb==0)
r[j]=xor(r[j],z[k]);
else
r[j]=xor(r[j],g[k]);
k++;
}
r[m+i]=d[m+i];
}

System.out.print("\nTHE CODE BITS ADDED


ARE:"); for(i=n;i<n+m-1;i++)
{
d[i]=r[i];
System.out.print(d[i]);
}
System.out.println("");

System.out.print("\nTHE CODE DATA IS:");


for(i=0;i<n+m-1;i++)
{
System.out.print(d[i]);
}
System.out.println("");
}
public static int xor(int x,int y){
if(x==y)
return(0);
else
return(1);
}

RESULT:

Thus the error detection/error correction techniques were implemented successfully.

You might also like