0% found this document useful (0 votes)
25 views

Computer Networks Record

computer networks
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Computer Networks Record

computer networks
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 93

ARIFA INSTITUTE OF TECHNOLOGY

(Approved by AICTE, New Delhi and affiliated to Anna University, Chennai)

Esanoor, Keezhaiyur (Po), Thirukkuvalai (Tk)


Nagapattinam (Dist) 611 103,

RECORD NOTE
Name : …………………………………………..

Reg. No. : …………………………………………..

Year / Sem : ……………………………………………..

Branch : ……………………………………………..

Course Code & Title : …………………………………………………..


ARIFA INSTITUTE OF TECHNOLOGY,
Esanoor – 611 103

Keezhaiyur – Po, Thirukkuvalai – Tk, Nagapattinam – Dt.


(Approved by AICTE, New Delhi and Affiliated to Anna University, Chennai)

BONAFIDE CERTIFICATE
Certified that this is the Bonafide record of work done by Mr /
Miss……………………………………………………………..
Reg.No……………………….………. of ................................................................ Sem /
………. Year Department ....................................................................... in

the ..........................................................................Laboratory during the

academic year 2023 – 2024.

HEAD OF THE DEPARTMENT STAFF INCHARGE

Submitted for the Anna University Practical Examination held at, Arifa
Institute of Technology, Esanoor, on ………………………..

INTERNAL EXAMINER EXTERNAL EXAMINER


CONTENTS
S.NO DATE NAME OF THE EXPERIMENT PAGE MARKS SIGN REMARKS
NO
S.NO DATE NAME OF THE EXPERIMENT PAGE MARKS SIGN REMARKS
NO

TOTAL MARKS

AVERAGE MARKS

Sl No Contents Maximum Marks


Marks Obtained
1 Attendance
2 Observation
3 Record
Total

Date: signature of staff incharge


EX.NO:1 CAPTURE THE PING & TRACEOUT PDUS USING
DATE : NETWORK PROTOCOL ANALYZER & EXAMINE

AIM:

To Write the java program for simulating ping and traceout command

ALGORITHM:

Step 1: start the program.

Step 2: Include necessary package in java.

Step 3: To create a process object p to implement the ping command.

Step 4: declare one Buffered Reader stream class object.

Step 5: Get the details of the server

5.1: length of the IP address.

5.2: time required to get the details.

5.3: send packets , receive packets and lost packets.

5.4: minimum ,maximum and average times.

Step 6: print the results.

Step 7:Stop the program.


PROGRAM:-PING

import java.io.*;

import java.net.*;

class pingserver

public static void main(String args[])

try

String str;

System.out.print(" Enter the IP Address to be Ping : ");

BufferedReader buf1=new BufferedReader(new

InputStreamReader(System.in));

String ip=buf1.readLine();

Runtime H=Runtime.getRuntime();

Process p=H.exec("ping " + ip);

InputStream in=p.getInputStream();

BufferedReader buf2=new BufferedReader(new

InputStreamReader(in));

while((str=buf2.readLine())!=null)

System.out.println(" " + str);

}
}

OUTPUT:

Enter the IP address to the ping:192.168.0.1

Pinging 192.168.0.1: with bytes of data =32

Reply from 192.168.0.11:bytes=32 time<1ms TTL =128

Reply from 192.168.0.11:bytes=32 time<1ms TTL =128

Reply from 192.168.0.11:bytes=32 time<1ms TTL =128

Reply from 192.168.0.11:bytes=32 time<1ms TTL =128

Ping statistics for 192.168.0.1

Packets: sent=4,received=4,lost=0(0% loss),approximate round trip time


in milli seconds:

Minimum=1

ms,maximum=4ms,average=2ms
PROGRAM:-TRACEOUT

import java.io.*;
import java.net.*;
import java.lang.*;
class Traceroute
{
public static void main(String args[]){
BufferedReader in;
try{
Runtime r = Runtime.getRuntime();
Process p = r.exec("tracert www.google.com");
in=new BufferedReader(newInputStreamReader(p.getInputStream());
String line;
if(p==null)
System.out.println("could not connect");
while((line=in.readLine())!=null){
System.out.println(line);
//in.close();
}
}
catch(IOException e)
{
System.out.println(e.toString());

}
}
}
OUTPUT:

Tracing route to www.google.com [74.125.28.106]


over a maximum of 30 hops:

1 70 ms 55 ms 70 ms 10.228.129.13
2 87 ms 84 ms 10.228.149.14
3 82 ms 85 ms 116.202.226.145
4 95 ms 94 ms 136 ms 10.228.158.82
5 Request timed out.
6 53 ms 55 ms 59 ms 116.202.226.21
7 85 ms 74 ms 82 ms 72.14.205.145
8 76 ms 75 ms 71 ms 72.14.235.69
9 124 ms 114 ms 113 ms 216.239.63.213
10 181 ms 194 ms 159 ms 66.249.95.132
11 285 ms 247 ms 246 ms 209.85.142.51
12 288 ms 282 ms 283 ms 72.14.233.138
13 271 ms 283 ms 274 ms 64.233.174.97
14 Request timed out.
15 269 ms 273 ms 283 ms pc-in-f106.1e100.net [74.125.28.106]

Trace complete.

RESULT:

Thus the commands like tcpdump, netstat, if config, is lookup and traceoute are
used then ping and traceoute PDUs using network protocol is successfully
executed
EX.NO:2 HTTP Web Client program to download a web page
DATE: using TCP Socket

AIM:

To write a HTTP Web Client program to download a web page using


TCP Socket

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 will send NACK signal to client.

6.Stop the program


PROGRAM :

CLIENT:

import javax.swing.*;

import java.net.*;

import java.awt.image.*;

import javax.imageio.*;

import java.io.*;

import java.awt.image.BufferedImage;

import java.io.ByteArrayOutputStream;

import java.io.File;

import java.io.IOException;

import javax.imageio.ImageIO;

public class Client

public static void main(String args[]) throws Exception

Socket soc;

BufferedImageimg= null; soc=new Socket(&quot;localhost&quot;,4000);

System.out.println(&quot;Client is running. &quot;);

try

System.out.println(&quot;Reading image from disk. &quot;);

Img=ImageIO.read(new

ile(&quot;digital_image_processing.jpg&quot;));
ByteArrayOutputStream baos = new ByteArrayOutputStream();

ImageIO.write(img, &quot;jpg&quot;, baos); baos.flush();

byte[] bytes = baos.toByteArray(); baos.close();

System.out.println(&quot;Sending image to server. &quot;);


OutputStream out =

soc.getOutputStream();

DataOutputStreamdos=NewDataOutputStream(out);
dos.writeInt(bytes.length);

dos.write(bytes, 0, bytes.length);

System.out.println(&quot;Image sent to server. &quot;);

dos.close(); out.close();

catch (Exception e)

System.out.println(&quot;Exception: &quot; + e.getMessage());

soc.close();

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(&quot;Server Waiting for image&quot;);

socket=server.accept();

System.out.println(&quot;Client connected.&quot;);

InputStream in = socket.getInputStream();

DataInputStream dis = new DataInputStream(in);

int len = dis.readInt();

System.out.println(&quot;Image Size: &quot; + len/1024 +


&quot;KB&quot;); 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(&quot;Server&quot;);

ImageIcon icon = new ImageIcon(bImage);

JLabel l = new JLabel();

l.setIcon(icon);

f.add(l);

f.pack();

f.setVisible(true);

OUTPUT:

Server Waiting For Image

Client Connected

ImageSize:29MB

RESULT:

Thus the HTTP web program to download web page using TCP sockets was
excecuted successfully
EX.NO:3(a) APPLICATION USING TCP SOCKETS LIKE ECHO-
DATE: CLIENT AND ECHO -SERVER

AIM:

To write a java program for Echo-client and Echo-server using TCP


Sockets

Links

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 will send NACK signal to client.

6.Stop the program


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

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!");

}
OUTPUT:

Server:

C:\Program Files\Java\jdk1.5.0\bin>javac EServer.java

Note: EServer.java uses or overrides a deprecated API.

Note: Recompile with -deprecation for details.

C:\Program Files\Java\jdk1.5.0\bin>java EServer

C:\Program Files\Java\jdk1.5.0\bin>

Client:

C:\Program Files\Java\jdk1.5.0\bin>javac EClient.java

Note: EClient.java uses or overrides a deprecated API.

Note: Recompile with -deprecation for details.

C:\Program Files\Java\jdk1.5.0\bin>java EClient

Client:

Hai Server

Server:Hai Server

Client:

Hello

Server:Hello

Client:

end

Server:end

Client: ds Socket Closed!

RESULT:

Thus the application using TCP sockets like Echo-server and Echo-client was
executed successfully
EX.NO:3(b) Application using TCP sockets like chat

DATE:

AIM:

To develop a chat server and client program in Java using TCP socket.

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.

5. Repeat step 3-4 until the client end.

6. Close the stream.

7. Close the server and client socket.

8. Stop.
CLIENT:

1. Create the client socket and establish connection with server.

2. Get a message from user and send it to server.

3. Read all inputs / outputs stream.

4. Close the client socket.

5. Stop.

CLIENT PROGRAM:

import java.io.*;

import java.net.*;

public class chatclient

public static void main (String args[]) throws Exception

Socket sock = new Socket("172.16.15.19",3000);

BufferedReader KeyRead = new BufferedReader(new


InputStreamReader(System.in));

OutputStream ofstream = sock.getOutputStream();

PrintWriter pwrite = new PrintWriter(ofstream,true);

InputStream istream=sock.getInputStream();

BufferedReader receivedread=new BufferedReader(new


InputStreamReader(istream));

System.out.println("client ready for chatting");


String receivemessage,sendmessage;

while(true)

sendmessage=KeyRead.readLine();

pwrite.println(sendmessage);

System.out.flush();

if((receivemessage=receivedread.readLine())!=null)

System.out.println(receivemessage);

SERVER PROGRAM:

import java.io.*;

import java.net.*;

public class chatserver

public static void main(String args[])throws Exception

ServerSocket sersock=new ServerSocket(3000);

System.out.println("Server ready for chatting");

Socket sock=sersock.accept();

BufferedReader KeyRead = new BufferedReader(new


InputStreamReader(System.in));
OutputStream ofstream=sock.getOutputStream();

PrintWriter pwrite=new PrintWriter(ofstream,true);

InputStream istream=sock.getInputStream();

BufferedReader receivedread = new BufferedReader(new


InputStreamReader(istream));

String receivemessage,sendmessage;

while(true)

if((receivemessage = receivedread.readLine())!=null)

System.out.println(receivemessage);

sendmessage=KeyRead.readLine();

pwrite.println(sendmessage);

System.out.flush();

}
CHATCLIENT:
Nicrosoft Windos tUersion 6.1.7601
Coperight ic) 280 Microsof t Corporat ion.
A11 rights reserved
CENUsers\student d:
D:Nset path-"D:\Java\jdk1.7.0_55";
D:Nset class path="D:\Java\jdk1.7.8_55\lib'"';
D:Ned D:dava\jdk1.?.055Nbin
D:Javajdki.7.0_55Nbin >javac chatclient . java
D:Javajdki.7.8 55 bin>java chatclient
client ready for chatting
e Icone

to
to AIT

CHATSERVER:

Microsof t Windows [Version 6.1.76011


Copyright (c) 2889 Microsoft Corporation .
All rights reserved.
C:NUsersstudent >d:
D:NSet path= "D : NJava\jdki.7.8 55";
D:NSET classpath="D : NJava jdki.7.0_55Nlib'';
D:Ncd D:Java jdki.?.0 55Nbin
D:NJavajdki.7.8 55Nbin >javac chatserver.java
D:NJava jdk1.7.8 55\bin>java chatserver
Server ready for chatting
welcome
to
to AIT

RESULT:
Thus the application using TCP sockets like chat was executed successfully
EX.NO:3(c) Application of using TCP sockets like File Transfer
DATE :

AIM:
To write a java program for file transfer using TCP Sockets.
ALGORITHM:
Server:
Step1: Import java packages and create class file server.
Step2: Create a new server socket and bind it to the port.
Step3: Accept the client connection
Step4: Get the file name and stored into the BufferedReader.
Step5: Create a new object class file and realine.
Step6: If file is exists then FileReader read the content until EOF is
reached.
Step7: Stop the program.
Client:
Step1: Import java packages and create class file server.
Step2: Create a new server socket and bind it to the port.
Step3: Now connection is established.
Step4: The object of a BufferReader class is used for storing data content
which has been retrieved from socket object.
Step5: The content of file is displayed in the client window and the
connection is closed.
Step6: Stop the program
FILE CLIENT

Import java.io.*;

Import java.net.*;

Import java.util.*;

Class Clientfile

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 file name:");

String str=in.readLine();

dout.writeBytes(str+'\n');

System.out.println("Enter the new file name:");

String str2=in.readLine();

String str1,ss;

FileWriter f=new

FileWriter(str2); char buffer[];

while(true)
{ str1=din.readLine();

if(str1.equals("-1")) break;

System.out.println(str1);

buffer=new char[str1.length()];

str1.getChars(0,str1.length(),buffer,0);

f.write(buffer);

f.close();

clsct.close();

catch (Exception e)

System.out.println(e);

}}}

SERVER

import java.io.*;

import java.net.*;

import java.util.*;

class Serverfile

{ public static void main(String args[])

Try

ServerSocket obj=new ServerSocket(139); while(true)


{

Socket obj1=obj.accept();

DataInputStream din=new DataInputStream(obj1.getInputStream());

DataOutputStream

dout=new DataOutputStream(obj1.getOutputStream());

String str=din.readLine();

FileReader f=new FileReader(str);

BufferedReader b=new

BufferedReader(f); String s;

while((s=b.readLine())!=null) {

System.out.println(s);

dout.writeBytes(s+'\n');

f.close();

dout.writeBytes("-1\n");

}}

catch(Exception e)

{ System.out.println(e);}}}
OUTPUT:

File content Computer networks jhfcgsauf

jbsdava jbvuesagv client

Enter the file name: sample.txt

server

Computer networks jhfcgsauf

jbsdava jbvuesagv client

Enter the new file name: net.txt

Computer networks jhfcgsauf

jbsdava jbvuesagv Destination file

Computer networks jhfcgsauf

jbsdava jbvuesagv

RESULT:

Thus the java program file transfer application using TCP Sockets was
executed successfully.
EX.NO:4 Simulation of DNS using UDP Sockets

DATE:

Aim

To write a java program for Dns application program

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 will send 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);
DatagramPacketrecvpack=new
DatagramPacket(receivedata,receivedata.length);

clientsocket.receive(recvpack);

String modified = new String(recvpack.getData());

System.out.println("IP Address: " + modified);

clientsocket.close();

}}
OUTPUT:

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 simulation of DNS using UDP sockets was successfully executed.
EX.NO:5 Write a code simulating ARP/RARP Protocol

DATE:

AIM:

To write a java program for simulating ARP/RARP protocols

ALGORITHM:

SERVER:

1. Create a server socket and bind it to port.

2. Listen for new connection and when a connection arrives, accept it.

3. Send server‟s date and time to the client.

4. Read client‟s IP address sent by the client.

5. Display the client details.

6. Repeat steps 2-5 until the server is terminated.

7. Close all streams.

8. Close the server socket.

9. Stop.

CLIENT:

1. Create a client socket and connect it to the server‟s port number.

2. Retrieve its own IP address using built-in function.

3. Send its address to the server.

4. Display the date & time sent by the server.

5. Close the input and output streams.

6. Close the client socket

.7. Stop.
PROGRAM

Program for Address Resolutuion Protocol (ARP) using TCP

CLIENT:

import java.io.*;

import java.net.*;

import java.util.*;

class Clientarp

public static void main(String args[])

try

BufferedReaderin=newBufferedReader(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):");

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

ServerSocket obj=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:
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


Program for Reverse Address Resolutuion Protocol (RARP) using UDP

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];

BufferedReaderin=newBufferedReader(new
InputStreamReader(System.in));

System.out.println("Enter the Physical address (MAC):");

String str=in.readLine();

sendbyte=str.getBytes();

DatagramPacket sender=new

DatagramPacket(sendbyte,sendbyte.length,addr,1309);

client.send(sender);

DatagramPacketreceiver=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();

//System.out.println(s);

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;

catch(Exception e)

System.out.println(e);

}
OUTPUT:

I:\ex>java Serverrarp12

I:\ex>java Clientrarp12

Enter the Physical address (MAC):

6A:08:AA:C2

The Logical Address is(IP): 165.165.80.80

RESULT:

Thus the program for implementing to display simulating ARP /RARP


protocols
EX.NO:6 Study of Network simulator (NS) and Congestion
DATE: control algorithm using NS

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

NET WORK SIMULATOR (NS2):


NS OVERVIEW :
 Ns programming:A Quick start
 Case study I:A simple Wireless network
 Case study II: Create a new agent in Ns
 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
WIRELESS:
Ad hoc routing, mobile IP, sensor-MAC Tracing, visualization and
various utilitiesNS(Network Simulators) Most of the commercial simulators are
GUI driven, while some network simulators are CLI driven. The network model
/ configuration describe the state of the network (nodes, routers, switchesand
links) and the events (data transmissions, packet error etc.). The important
outputs 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 buffer overflow in a network, the time required for an accurate answer can
be extremely large. Specialized techniques such as "control variants" and
"importance sampling" have been developed to speed simulation.
 ns (open source)
 OPNET (proprietary software)
 NetSim (proprietary software)

USES OF NETWORK SIMULATORS:


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. 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, analyse 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.
THROUGHPUT:
This 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 success full message
delivery over a communication channel. The throughput is usually measured in
bit per second (bit/s or bps), and sometime sin data packet per second or data
packets per time slot This measure 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
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 high bandwidths. 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.

RESULT:
Thus the study of Network simulator (NS2) was studied
Ex: No:7 STUDY OF TCP/UDP PERFORMANCE USING SIMULATION
DATE: TOOL

TCP Protocol – Introduction

The TCP/IP Reference Model


TCP/IP means Transmission Control Protocol and Internet Protocol. It is the network
model used in the current Internet architecture as well. Protocols are set of rules which
govern every possible communication over a network. These protocols describe the
movement of data between the source and destination or the internet. They also offer simple
naming and addressing schemes .

Protocols and networks in the TCP/IP model:

Overview of TCP/IP reference model


TCP/IP that is Transmission Control Protocol and Internet Protocol was developed by
Department of Defence's Project Research Agency (ARPA, later DARPA) as a part of a
research project of network interconnection to connect remote machines.
The features that stood out during the research, which led to making the TCP/IP reference
model were:
 Support for a flexible architecture. Adding more machines to a network was easy.
 The network was robust, and connections remained intact untill the source and
destination machines were functioning.

The overall idea was to allow one application on one computer to talk to(send data packets)
another application running on different computer.
TCP Header:

The following diagram represents the TCP header format-

1. Source Port-

 Source Port is a 16 bit field.


 It identifies the port of the sending application.

2. Destination Port-

 Destination Port is a 16 bit field.


 It identifies the port of the receiving application.
3. Sequence Number-

 Sequence number is a 32 bit field.


 TCP assigns a unique sequence number to each byte of data contained in the TCP
segment.
 This field contains the sequence number of the first data byte.
4. Acknowledgement Number-

 Acknowledgment number is a 32 bit field.


 It contains sequence number of the data byte that receiver expects to receive next from
the sender.
 It is always sequence number of the last received data byte incremented by 1.

5. Header Length-

 Header length is a 4 bit field.


 It contains the length of TCP header.
 It helps in knowing from where the actual data begins.

Minimum and Maximum Header length-

The length of TCP header always lies in the range-


[20 bytes , 60 bytes]

 The initial 5 rows of the TCP header are always used.


 So, minimum length of TCP header = 5 x 4 bytes = 20 bytes.
 The size of the 6th row representing the Options field vary.
 The size of Options field can go up to 40 bytes.
 So, maximum length of TCP header = 20 bytes + 40 bytes = 60 bytes.

Concept of Scaling Factor-

 Header length is a 4 bit field.


 So, the range of decimal values that can be represented is [0, 15].
 But the range of header length is [20, 60].
 So, to represent the header length, we use a scaling factor of 4.

In general,

Header length = Header length field value x 4 bytes


TCP Connection Establishment Protocol:
TCP Connection Establishment

Prerequisite – TCP 3-Way Handshake Process


TCP is a connection oriented protocol and every connection oriented protocol needs to
establish connection in order to reserve resources at both the communicating ends.

Connection Establishment –
1. Sender starts the process with following:
 Sequence number (Seq=521): contains the random initial sequence number
which generated at sender side.
 Syn flag (Syn=1): request receiver to synchronize its sequence number with the
above provided sequence number.
 Maximum segment size (MSS=1460 B): sender tells its maximum segment size,
so that receiver sends datagram which won’t require any fragmentation. MSS
field is present inside Option field in TCP header.
 Window size (window=14600 B): sender tells about his buffer capacity in which
he has to store messages from receiver.

2. TCP is a full duplex protocol so both sender and receiver require a window for
receiving messages from one another.
 Sequence number (Seq=2000): contains the random initial sequence number
which generated at receiver side.
 Syn flag (Syn=1): request sender to synchronize its sequence number with the
above provided sequence number.
 Maximum segment size (MSS=500 B): sender tells its maximum segment size, so
that receiver sends datagram which won’t require any fragmentation. MSS field is
present inside Option field in TCP header.
Since MSSreceiver < MSSsender, both parties agree for minimum MSS i.e., 500 B to
avoid fragmentation of packets at both ends.
 Therefore, receiver can send maximum of 14600/500 = 29 packets.

This is the receiver's sending window size.


 Window size (window=10000 B): receiver tells about his buffer capacity in which
he has to store messages from sender.
 Therefore, sender can send a maximum of 10000/500 = 20 packets.
This is the sender's sending window size.
 Acknoledgement Number (Ack no.=522): Since sequence number 521 is received
by receiver so, it makes a request of next sequence number with Ack no.=522
which is the next packet expected by receiver since Syn flag consumes 1 sequence
no.
 ACK flag (ACk=1): tells that acknowledgement number field contains the next
sequence expected by receiver.
3.Sender makes the final reply for connection establishment in following way:
 Sequence number (Seq=522): since sequence number = 521 in 1st step and SYN
flag consumes one sequence number hence, next sequence number will be 522.
 Acknowledgement Number (Ack no.=2001): since sender is acknowledging SYN=1
packet from the receiver with sequence number 2000 so, the next sequence
number expected is 2001.
 ACK flag (ACK=1): tells that acknowledgement number field contains the next
sequence expected by sender.

Since the connection establishment phase of TCP makes use of 3 packets, it is also known
as 3-way Handshaking (SYN, SYN + ACK, ACK).
TCP Socket Options:

Introduction
There are various ways to get and set the options that affect a socket:

 The getsockopt and setsockopt functions.


 The fcntl function, which is the POSIX way to set a socket for nonblocking I/O, signal-
driven I/O, and to set the owner of a socket.
 The ioctl function.

getsockopt and setsockopt Functions


Arguments:

 sockfd must refer to an open socket descriptor.


 level specifies the code in the system that interprets the option: the general socket
code or some protocol-specific code (e.g., IPv4, IPv6, TCP, or SCTP).
 optval is a pointer to a variable from which the new value of the option is fetched
by setsockopt, or into which the current value of the option is stored by getsockopt.
The size of this variable is specified by the final argument optlen, as a value
for setsockopt and as a value-result for getsockopt.

The following table lists socket and IP-layer socket options for getsockopt and setsockopt.

Level optname get set Description Flag Datatype

SOL_ SO_BROADCAST x x Permit x int


SOC sending of
KET broadcast
datagrams

SO_DEBUG x x Enable x int


debug
tracing

SO_DONTROUTE x x Bypass x int


routing table
lookup

SO_ERROR x Get pending int


error and
Level optname get set Description Flag Datatype

clear

SO_KEEPALIVE x x Periodically x int


test if
connection
still alive

SO_LINGER x x Linger on linger{}


close if data
to send

SO_OOBINLINE x x Leave x int


received
out-of-band
data inline

SO_RCVBUF x x Receive int


buffer size

SO_SNDBUF x x Send buffer int


size

SO_RCVLOWAT x x Receive int


buffer low-
water mark

SO_SNDLOWAT x x Send buffer int


low-water
mark

SO_RCVTIMEO x x Receive timeval{}


Level optname get set Description Flag Datatype

timeout

SO_SNDTIMEO x x Send timeval{}


timeout

SO_REUSEADDR x x Allow local x int


address
reuse

SO_REUSEPORT x x Allow local x int


port reuse

SO_TYPE x Get socket int


type

SO_USELOOPBACK x x Routing x int


socket gets
copy of what
it sends

IPPR IP_HDRINCL x x IP header x int


OTO included
_IP with data

IP_OPTIONS x x IP header (see text)


options

IP_RECVDSTADDR x x Return x int


destination
IP address
Level optname get set Description Flag Datatype

IP_RECVIF x x Return x int


destination
IP address

IP_TOS x x Type-of- int


service and
precedence

IP_TTL x x TTL int

IP_MULTICAST_IF x x Specify in_addr{}


outgoing
interface

IP_MULTICAST_TTL x x Specify u_char


outgoing TTL

IP_MULTICAST_LOOP x x Specify u_char


loopback

IP_{ADD,DROP}_MEMBERS x Join or leave ip_mreq{}


HIP multicast
group

IP_{BLOCK,UNBLOCK}_SO x Block or ip_mreq_source{}


URCE unblock
multicast
source

IP_{ADD,DROP}_SOURCE_ x Join or leave ip_mreq_source{}


MEMBERSHIP source-
specific
Level optname get set Description Flag Datatype

multicast

IPPR ICMP6_FILTER x x Specify icmp6_filter{}


OTO ICMPv6
_ICM message
PV6 types to pass

IPPR IPV6_CHECKSUM x x Offset of int


OTO checksum
_IPV field for raw
6 sockets

IPV6_DONTFRAG x x Drop instead x int


of fragment
large
packets

IPV6_NEXTHOP x x Specify next- sockaddr_in6{}


hop address

IPV6_PATHMTU x Retrieve ip6_mtuinfo{}


current path
MTU

IPV6_RECVDSTOPTS x Receive x int


destination
options

IPV6_RECVHOPLIMIT x x Receive x int


unicast hop
limit
Level optname get set Description Flag Datatype

IPV6_RECVHOPOPTS x x Receive hop- x int


by-hop
options

IPV6_RECVPATHMTU x x Receive path x int


MTU

IPV6_RECVPKTINFO x x Receive x int


packet
information

IPV6_RECVRTHDR x x Receive x int


source route

IPV6_RECVTCLASS x x Receive x int


traffic class

IPV6_UNICAT_HOPS x x Default int


unicast hop
limit

IPV6_USE_MIN_MTU x x Use x int


minimum
MTU

IPV6_V6ONLY x x Disable v4 x int


compatibility

IPV6_XXX x x Sticky (see text)


ancillary
data
Level optname get set Description Flag Datatype

IPV6_MULTICAST_IF x x Specify u_int


outgoing
interface

IPV6_MULTICAST_HOPS x x Specify int


outgoing
hop limit

IPV6_MULTICAST_LOOP x x Specify x u_int


loopback

IPV6_JOIN_GROUP x Join ipv6_mreq{}


multicast
group

IPV6_LEAVE_GROUP x Leave ipv6_mreq{}


multicast
group

IPPR MCAST_JOIN_GROUP x Join group_req{}


OTO multicast
_IP o group
r IPP
ROT
O_IP
V6

MCAST_LEAVE_GROUP x Leave group_source_req{}


multicast
group
Level optname get set Description Flag Datatype

MCAST_BLOCK_SOURCE x Block group_source_req{}


multicast
source

MCAST_UNBLOCK_SOURC x Unblock group_source_req{}


E multicast
source

MCAST_JOIN_SOURCE_GRO x Join source- group_source_req{}


UP specific
multicast

MCAST_LEAVE_SOURCE_G x Leave group_source_req{}


ROUP source-
specific
multicast

NS2 – Code for TCP Operations:


Network simulation (NS) is one of the types of simulation, which is used to simulate the
networks such as in MANETs, VANETs etc. It provides simulation for routing and multicast
protocols for both wired and wireless networks. NS is licensed for use under version 2 of the
GNU (General Public License) and is popularly known as NS2. It is an object-oriented,
discrete event-driven simulator written in C++ and Otcl/tcl.
NS-2 can be used to implement network protocols such as TCP and UPD, traffic source
behavior such as FTP, Telnet, Web, CBR and VBR, router queue management mechanism
such as Drop Tail, RED and CBQ, routing algorithms and many more. In ns2, C++ is used
for detailed protocol implementation and Otcl is used for the setup. The compiled C++
objects are made available to the Otcl interpreter and in this way, the ready-made C++
objects can be controlled from the OTcl level.

Install NS-2 using this command :


sudo apt-get install ns2
Nam is also needed to install. Nam (Network Animator) is an animation tool to graphically
represent the network and packet traces. Use this command :
sudo apt-get install nam
Some basic Otcl script syntax :

 Basic Command :
filter_none

brightness_4
set a 8

set b [expr $a/8]

Explanation : In the first line, the variable a is assigned the value 8. In the second line,
the result of the command [expr $a/8], which equals 1, is then used as an argument to
another command, which in turn assigns a value to the variable b. The “$” sign is used
to obtain a value contained in a variable and square brackets are an indication of a
command substitution.

 Define new procedures with proc command


filter_none

brightness_4
proc factorial fact {

if {$fact <= 1} {

return 1

expr $fact * [factorial [expr $fact-1]]

 To open a file for reading :


filter_none

brightness_4
set testfile [open hello.dat r]

Similarly, put command is used to write data into the file


filter_none

brightness_4
set testfile [open hello.dat w]

puts $testfile “hello1”

 To call subprocesses within another process, exec is used, which creates a subprocess
and waits for it to complete.
filter_none

brightness_4
exec rm $testfile

 To be able to run a simulation scenario, a network topology must first be created. In


ns2, the topology consists of a collection of nodes and links.
filter_none

brightness_4
set ns [new Simulator]

 The simulator object has member functions which enables to create the nodes and
define the links between them. The class simulator contains all the basic functions.
Since ns was defined to handle the Simulator object, the command $ns is used for
using the functions belonging to the simulator class.
In the network topology nodes can be added in the following manner :
filter_none

brightness_4
set n0 [$ns node]

set n1 [$ns node]

 Traffic agents (TCP, UDP etc.) and traffic sources (FTP, CBR etc.) must be set up if the
node is not a router. It enables to create CBR traffic source using UDP as transport
protocol or an FTP traffic source using TCP as a transport protocol.
CBR traffic source using UDP :
filter_none

brightness_4
set udp0 [new Agent/UDP]
$ns attach-agent $n0 $udp0

set cbr0 [new Application/Traffic/CBR]

$cbr0 attach-agent $udp0

$cbr0 set packet_size_ 512

FTP traffic source using TCP :

filter_none

brightness_4
set tcp0 [new Agent/TCP]

$ns attach-agent $n0 $tcp0

set ftp0 [new Application/FTP]

$ftp0 attach-agent $tcp0

$tcp0 set packet_size_ 512

Below is the implementation of creating links between the source and destination using
both ftp and tcp :
filter_none

brightness_4
# Create a simulator object

set ns [new Simulator]

# Define different colors

# for data flows (for NAM)

$ns color 1 Blue

$ns color 2 Red

# Open the NAM trace file

set nf [open out.nam w]

$ns namtrace-all $nf


# Define a 'finish' procedure

proc finish {}

global ns nf

$ns flush-trace

# Close the NAM trace file

close $nf

# Execute NAM on the trace file

exec nam out.nam &

exit 0

# Create four nodes

set n0 [$ns node]

set n1 [$ns node]

set n2 [$ns node]

set n3 [$ns node]

# Create links between the nodes

$ns duplex-link $n0 $n2 2Mb 10ms DropTail

$ns duplex-link $n1 $n2 2Mb 10ms DropTail

$ns duplex-link $n2 $n3 1.7Mb 20ms DropTail

# Set Queue Size of link (n2-n3) to 10


$ns queue-limit $n2 $n3 10

# Give node position (for NAM)

$ns duplex-link-op $n0 $n2 orient right-down

$ns duplex-link-op $n1 $n2 orient right-up

$ns duplex-link-op $n2 $n3 orient right

# Monitor the queue for link (n2-n3). (for NAM)

$ns duplex-link-op $n2 $n3 queuePos 0.5

# Setup a TCP connection

set tcp [new Agent/TCP]

$tcp set class_ 2

$ns attach-agent $n0 $tcp

set sink [new Agent/TCPSink]

$ns attach-agent $n3 $sink

$ns connect $tcp $sink

$tcp set fid_ 1

# Setup a FTP over TCP connection

set ftp [new Application/FTP]

$ftp attach-agent $tcp

$ftp set type_ FTP

# Setup a UDP connection


set udp [new Agent/UDP]

$ns attach-agent $n1 $udp

set null [new Agent/Null]

$ns attach-agent $n3 $null

$ns connect $udp $null

$udp set fid_ 2

# Setup a CBR over UDP connection

set cbr [new Application/Traffic/CBR]

$cbr attach-agent $udp

$cbr set type_ CBR

$cbr set packet_size_ 1000

$cbr set rate_ 1mb

$cbr set random_ false s

# Schedule events for the CBR and FTP agents

$ns at 0.1 "$cbr start"

$ns at 1.0 "$ftp start"

$ns at 4.0 "$ftp stop"

$ns at 4.5 "$cbr stop"

# Detach tcp and sink agents

# (not really necessary)

$ns at 4.5 "$ns detach-agent $n0 $tcp ; $ns detach-agent $n3 $sink"
# Call the finish procedure after

# 5 seconds of simulation time

$ns at 5.0 "finish"

# Print CBR packet size and interval

puts "CBR packet size = [$cbr set packet_size_]"

puts "CBR interval = [$cbr set interval_]"

# Run the simulation

$ns run

Output :
Conclusion:

Now that we've discussed some of the major components of networks and TCP/IP, you
have the necessary background to examine the more critical issues of security in a
converged environment. Knowing how networks are built gives you a better
understanding of what physical or logical vulnerabilities are introduced by choosing one
particular network design over another. Knowing how packets are formed gives you a
better understanding of how they can be crafted or modified to achieve a specific
purpose. Knowing how packets are transmitted and delivered gives you a better
understanding of what can happen to packets as they travel from source to destination.
A good understanding of the basics of networking and TCP/IP is critical to identifying,
understanding, and correcting vulnerabilities in your converged environment.

CASE STUDY – 2

STUDY OF UDP PERFORMANCE

UDP Protocol – Introduction:

Techopedia explains User Datagram Protocol (UDP)

User datagram protocol is an open systems interconnection (OSI) transport layer protocol for
client- server network applications. UDP uses a simple transmission model but does not
employ handshaking dialogs for reliability, ordering and data integrity. The protocol assumes
that error-checking and correction is not required, thus avoiding processing at the network
interface level.
UDP is widely used in video conferencing and real-time computer games. The protocol
permits individual packets to be dropped and UDP packets to be received in a different
order than that in which they were sent, allowing for better performance.

UDP network traffic is organized in the form of datagrams, which comprise one message
units. The first eight bytes of a datagram contain header information, while the remaining
bytes contain message data. A UDP datagram header contains four fields of two bytes each:

 Source port number


 Destination port number
 Datagram size
 Checksum
UDP Header:

UDP header is 8-bytes fixed and simple header, while for TCP it may vary from 20 bytes to
60 bytes. First 8 Bytes contains all necessary header information and remaining part consist
of data. UDP port number fields are each 16 bits long, therefore range for port numbers
defined from 0 to 65535; port number 0 is reserved. Port numbers help to distinguish
different user requests or process.

1. Source Port : Source Port is 2 Byte long field used to identify port number of source.
2. Destination Port : It is 2 Byte long field, used to identify the port of destined packet.
3. Length : Length is the length of UDP including header and the data. It is 16-bits field.
4. Checksum : Checksum is 2 Bytes long field. It is the 16-bit one’s complement of the
one’s complement sum of the UDP header, pseudo header of information from the IP
header and the data, padded with zero octets at the end (if necessary) to make a
multiple of two octets.

UDP Socket Options:


NS2 – Code f Description

UDP socket routines enable simple IP communication using the user datagram protocol
(UDP).

The User Datagram Protocol (UDP) runs on top of the Internet Protocol (IP) and was
developed for applications that do not require reliability, acknowledgment, or flow control
features at the transport layer. This simple protocol provides transport layer addressing in the
form of UDP ports and an optional checksum capability.

This documentation is separated as follows:

 User API describes the operation of UDP Sockets.


 Configuration explains the configuration options of the UDP Sockets.
UDP Operations:

One important topic under the exam number 300-101 route is on how to describe UDP
operations. It comes under the main topic of network principals. We will now in this chapter
try to discuss the many aspects of the topic so that you can clear this section and get a better
score. UDP is user datagram protocol.
What UDP exactly does is that it takes the data from the higher layer protocols and then
places them in the UDP messages. This is then passed down to the internet protocol for
transmission. It is a simple form of TCP/IP. Some of the steps that are followed in
transmission that is UDP based are as follows:
1. As a first step an application will send a message to the UDP software. This is also called the
higher layer data transfer.
2. The higher layer message that was sent in the first step will then be encapsulated into the
data field of the UDP message. After this the header of the UDP messages is filled in. This
includes the source port of the application that sent the data to the UDP as well as the
destination port. This will also help to calculate the checksum value. The checksum value
will allow detecting an error in a transmission if the UDP message was delivered to a wrong
destination.
3. In the last step the message is transferred to the IP. In this the UDP message will be passed
to the IP for further transmission.
The concept of UDP is simple. The UDP will not do the following. As a network
administrator you must be aware of these:
1. The UDP will never show any acknowledgement to prove that the data was received.
2. The UDP will never establish a connection before actually sending the data.
3. The UDP does not give a guarantee that the messages will arrive.
4. The UDP cannot detect the messages that were lost.
5. The UDP will also not assure that the data will be received in the same format as they were
received.
6. The UDP does not have any mechanism that manages flow of data between the devices and
does not handle congestion either.
The UDP messages will have the following parts:
1. Source port - this is a 16 bit port number of the process that initially originated the UDP
message on the source device.
2. Destination port - this is the second part of the message. It is a 16 bit-port number of the
process it is ultimate recipient of the message. This will generally be the port number of the
client.
3. Length -the length means the entire UDP datagram that includes data fields and the
headers.
4. Checksum - as we have already explained it before it is optional and generally 16 bit in size.
5. Data - it is the variable part of the UDP. It encapsulates the higher layer messages that need
to be sent.
Starvation
Generally the UDP based traffic and the TCP based traffic are not mixed for the best
performance of the network. This is done so that these two have different ways of behaving
under a time of congestion. It has been noted that when the TCP flows are combined with the
UDP flows in a single service provider class then congestion is almost inevitable.
This is because the TCP flows will continuously try to lower the transmission rates as a result
the bandwidth to the UDP flow will fall. This process is called TCP starvation or in other
words UDP dominance. This situation will mostly occur if the mission critical data that is
TCP based is assigned to the same service provider class as the UDP based streaming video
as a result the class will experience a sustained congestion.
It must be mentioned here that even the use of WERD cannot help these congestions. This is
mainly because WERD can manage congestion only on TCP based flows.
It is true no doubt that it is not always possible to separate the TCP and the UDP flow.
However, it is advisable that you know of what you can face in case you try to mix the two in
a single service provider class.

Latency

The latency is the interval between the response and the stimulation. The UDP is considered
to be much faster than the TCP. This is because the ACK allows a continuous stream of
packets.TCP on the other hand will recognise only a set of packets that makes it slower.
Some may feel that the UDP is faster and vice versa.
However, some experts belive that whether you go for a UDP or a TCP will depend on the
network features and the network traffic. Some say that TCP can work better in case of small
size writes. The TCP can control congestion but a UDP as we have already discussed do not
have a good congestion control mechanism.
If you want to improve the performance of the TCP throughput when there is UDP traffic
present then you can try one way and that is by opening many TCP connections. This will
ensure that the sum of the throughput of all the TCP connection will be greater than that of
the UDP.
The TCP and the UDP serve different requirements of the applications as a result they both
are mostly used. UDP can be very helpful in video conferencing where TCP is not a great
idea. UDP can also help in multicast. The TCP can keep multiple messages in a wire which is
not easily possible in UDP. The routers generally tend to drop the UDP before the TCP.
In most of the companies the UDP is dropped in order to improve the speed of the TCP. The
research is on to find new ways to balance the conflict between the software and we hope that
we will get a solution soon. Having two different infrastructures is a good idea but it is not
possible always as it will be a very expensive thing to do.
We have tried to discuss almost all the aspects that are important from the CCNP exam point
of view in this particular section. We hope that this chapter will help you to get a clearer
understanding of the topic.
Conclusion:

This thesis presents the client redirection problem and the requirements that should be met
by a good solution. These requirements include: transparency, scalability, maintainability,
and efficiency. Among three popular redirection mechanisms (HTTP redirection, TCP
handoff, and DNS redirection), we conclude that a DNS-based redirection mechanism meets
the four above requirements best.

Our implementation, called NetAirt, proves that with little effort Apache can be made to
service DNS packets, no matter which transport-layer protocol is used: UDP or TCP.
Moreover, our module can easily be integrated with an external replication-managing
component, designed either as a separate Apache module (like Globule, another project of
ours), or as a completely independent program.

We have paid attention to the development of a reasonable set of redirection policies: static
name-to-address mapping, round-robin replica selection, and the AS-path length policy. We
have incorporated them into NetAirt, thus demonstrating its flexibility, and allowing users to
switch between them. We have described in detail how the most advanced one, the AS-path
length policy, can be implemented. Firstly, BGP routing tables can be exploited to associate
an ASN with any IP address, as well as to build a map of the ASes. This map allows to define
the AS-path length metric, which is the base of the AS-path length redirection policy.

We have also conveyed two experiments. The first of them investigates the following three
issues: the impact of the transport protocol on the Round Trip Time (RTT) of a DNS packet,
the overhead introduced by running the round-robin address selection instead of the static
name-to-address mapping, and the correspondence between the number of IP addresses
returned in a single DNS response and the RTT. The results prove that sending DNS queries
over TCP is almost 80% slower than in case of UDP. On the other hand, the overhead
introduced by the round-robin policy, and the cost of responding with additional IP
addresses turn out to be negligible

RESULT:

Thus the study of TCP/UDP has been performed and verified successfully.
EX:NO:8 Simulation of Distance Vector Routing Algorithm

DATE:

AIM:

To simulate and study the Distance Vector routing algorithm using


simulation.

SOFTWARE REQUIRED:

NS-2

THEORY:

Distance Vector Routing is one of the routing algorithm in a Wide Area

Network for computing shortest path between source and destination. Th Router

is one main devices used in a wide area network. The main task of the router is

Routing. It forms the routing table and delivers the packets depending upon the

routes in the tableeither directly or via an intermediate devices. Each router

initially has information about its all neighbors. Then this information will be

shared among nodes.

ALGORITHM:

1. Create a simulator object

2. Define different colors for different data flows

3. Open a nam trace file and define finish procedure then close the trace

file, and execute nam on trace file.

4. Create n number of nodes using for loop

5. Create duplex links between the nodes

6. Setup UDP Connection between n(0) and n(5)

7. Setup another UDP connection between n(1) and n(5)


PROGRAM:

set ns [new Simulator]

set nr [open thro.tr w]

$ns trace-all $nr

set nf [open thro.nam w]

$ns namtrace-all $nf

proc finish { }

global ns nr nf

$ns flush-trace

close $nf

close $nr

exec nam thro.nam &amp;

exit 0

for { set i 0 } { $i &lt; 12} { incr i 1 } {

set n($i) [$ns node]}

for {set i 0} {$i &lt; 8} {incr i} {

$ns duplex-link $n($i) $n([expr $i+1]) 1Mb 10ms DropTail }

$ns duplex-link $n(0) $n(8) 1Mb 10ms DropTail

$ns duplex-link $n(1)

$n(10) 1Mb 10ms DropTail

$ns duplex-link $n(0) $n(9) 1Mb 10ms DropTail

$ns duplex-link $n(9) $n(11) 1Mb 10ms DropTail


$ns duplex-link $n(10) $n(11) 1Mb 10ms DropTail

$ns duplex-link $n(11) $n(5) 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(5)

$null0 $ns connect

$udp0 $null0 set udp1 [new Agent/UDP]

$ns attach-agent $n(1)

$udp1 set cbr1 [new Application/Traffic/CBR]

$cbr1 set packetSize_ 500

$cbr1 set interval_ 0.005

$cbr1 attach-agent

$udp1 set null0 [new Agent/Null]

$ns attach-agent $n(5)

$null0 $ns connect $udp1 $null0

$ns rtproto DV

$ns rtmodel-at 10.0 down $n(11) $n(5)

$ns rtmodel-at 15.0 down $n(7) $n(6)

$ns rtmodel-at 30.0 up $n(11) $n(5)


$ns rtmodel-at 20.0 up $n(7) $n(6)

$udp0 set fid_ 1

$udp1 set fid_ 2

$ns color 1 Red

$ns color 2 Green

$ns at 1.0 &quot;$cbr0 start&quot;

$ns at 2.0 &quot;$cbr1 start&quot;

$ns at 45 &quot;finish&quot;

$ns run
OUTPUT:

RESULT:

Thus the Distance vector Routing Algorithm was Simulated and studied.
EX.NO:9 Performance evaluation of routing protocol using
DATE: simulation tool

AIM:

To write a ns2 program for implementing unicast routing protocol and


multicast routing protocol.

ALGORITHM:

Step 1: start the program.

Step 2: declare the global variables ns for creating a new simulator.

Step 3: set the color for packets.

Step 4: open the network animator file in the name of file2 in the write

mode.

Step 5: open the trace file in the name of file 1 in the write mode.

Step 6: set the unicast routing protocol to transfer the packets in network.

Step 7: create the required no of nodes.

Step 8: create the duplex-link between the nodes including the delay

time,bandwidth and dropping. queue mechanism.

Step 9: give the position for the links between the nodes.

Step 10: set a tcp reno connection for source node.

Step 11: set the destination node using tcp sink.

Step 12: setup a ftp connection over the tcp connection.

Step 13: down the connection between any nodes at a particular time.

Step 14: reconnect the downed connection at a particular time.

Step 15: stop the program.


PROGRAM:-UNICAST ROUTING PROTOCOL

set ns [new Simulator]

#Define different colors for data flows (for NAM)

$ns color 1 Blue

$ns color 2 Red

#Open the Trace file

set file1 [open out.tr w]

$ns trace-all $file1

#Open the NAM trace file

set file2 [open out.nam w]

$ns namtrace-all $file2

#Define a 'finish' procedure

proc finish {} {

global ns file1 file2

$ns flush-trace

close $file1

close $file2

exec nam out.nam &

exit 3

# Next line should be commented out to have the static routing

$ns rtproto DV

#Create six nodes

set n0 [$ns node]


set n1 [$ns node]

set n2 [$ns node]

set n4 [$ns node]

set n4 [$ns node]

set n5 [$ns node]

#Create links between the nodes

$ns duplex-link $n0 $n1 0.3Mb 10ms DropTail

$ns duplex-link $n1 $n2 0.3Mb 10ms DropTail

$ns duplex-link $n2 $n3 0.3Mb 10ms DropTail

$ns duplex-link $n1 $n4 0.3Mb 10ms DropTail

$ns duplex-link $n3 $n5 0.5Mb 10ms DropTail

$ns duplex-link $n4 $n5 0.5Mb 10ms DropTail

#Give node position (for NAM)

$ns duplex-link-op $n0 $n1 orient right

$ns duplex-link-op $n1 $n2 orient right

$ns duplex-link-op $n2 $n3 orient up

$ns duplex-link-op $n1 $n4 orient up-left

$ns duplex-link-op $n3 $n5 orient left-up

$ns duplex-link-op $n4 $n5 orient right-up

#Setup a TCP connection

set tcp [new Agent/TCP/Newreno]

$ns attach-agent $n0 $tcp

set sink [new Agent/TCPSink/DelAck]

$ns attach-agent $n5 $sink


$ns connect $tcp $sink

$tcp set fid_ 1

#Setup a FTP over TCP connection

set ftp [new Application/FTP]

$ftp attach-agent $tcp

$ftp set type_ FTP

$ns rtmodel-at 1.0 down $n1 $n4

$ns rtmodel-at 4.5 up $n1 $n4

$ns at 0.1 "$ftp start"

$ns at 6.0 "finish"

$ns run
OUTPUT:
PROGRAM:-MULTICAST ROUTING PROTOCOL

# Create scheduler

#Create an event scheduler wit multicast turned on

set ns [new Simulator -multicast on]

#$ns multicast

#Turn on Tracing

set tf [open output.tr w]

$ns trace-all $tf

# Turn on nam Tracing

set fd [open mcast.nam w]

$ns namtrace-all $fd

# Create nodes

set n0 [$ns node]

set n1 [$ns node]

set n2 [$ns node]

set n3 [$ns node]

set n4 [$ns node]

set n5 [$ns node]

set n6 [$ns node]

set n7 [$ns node]

# Create links

$ns duplex-link $n0 $n2 1.5Mb 10ms DropTail

$ns duplex-link $n1 $n2 1.5Mb 10ms DropTail

$ns duplex-link $n2 $n3 1.5Mb 10ms DropTail


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

$ns duplex-link $n3 $n7 1.5Mb 10ms DropTail

$ns duplex-link $n4 $n5 1.5Mb 10ms DropTail

$ns duplex-link $n4 $n6 1.5Mb 10ms DropTail

# Routing protocol: say distance vector

#Protocols: CtrMcast, DM, ST, BST

set mproto DM

set mrthandle [$ns mrtproto $mproto {}]

# Allocate group addresses

set group1 [Node allocaddr]

set group2 [Node allocaddr]

# UDP Transport agent for the traffic source

set udp0 [new Agent/UDP]

$ns attach-agent $n0 $udp0

$udp0 set dst_addr_ $group1

$udp0 set dst_port_ 0

set cbr1 [new Application/Traffic/CBR]

$cbr1 attach-agent $udp0

# Transport agent for the traffic source

set udp1 [new Agent/UDP]

$ns attach-agent $n1 $udp1

$udp1 set dst_addr_ $group2

$udp1 set dst_port_ 0

set cbr2 [new Application/Traffic/CBR]


$cbr2 attach-agent $udp1

# Create receiver

set rcvr1 [new Agent/Null]

$ns attach-agent $n5 $rcvr1

$ns at 1.0 "$n5 join-group $rcvr1 $group1"

set rcvr2 [new Agent/Null]

$ns attach-agent $n6 $rcvr2

$ns at 1.5 "$n6 join-group $rcvr2 $group1"

set rcvr3 [new Agent/Null]

$ns attach-agent $n7 $rcvr3

$ns at 2.0 "$n7 join-group $rcvr3 $group1"

set rcvr4 [new Agent/Null]

$ns attach-agent $n5 $rcvr1

$ns at 2.5 "$n5 join-group $rcvr4 $group2"

set rcvr5 [new Agent/Null]

$ns attach-agent $n6 $rcvr2

$ns at 3.0 "$n6 join-group $rcvr5 $group2"

set rcvr6 [new Agent/Null]

$ns attach-agent $n7 $rcvr3

$ns at 3.5 "$n7 join-group $rcvr6 $group2"

$ns at 4.0 "$n5 leave-group $rcvr1 $group1"

$ns at 4.5 "$n6 leave-group $rcvr2 $group1"

$ns at 5.0 "$n7 leave-group $rcvr3 $group1"

$ns at 5.5 "$n5 leave-group $rcvr4 $group2"


$ns at 6.0 "$n6 leave-group $rcvr5 $group2"

$ns at 6.5 "$n7 leave-group $rcvr6 $group2"

# Schedule events

$ns at 0.5 "$cbr1 start"

$ns at 9.5 "$cbr1 stop"

$ns at 0.5 "$cbr2 start"

$ns at 9.5 "$cbr2 stop"

#post-processing

$ns at 10.0 "finish"

proc finish {} {

global ns tf

$ns flush-trace

close $tf

exec nam mcast.nam &

exit 0

# For nam

#Colors for packets from two mcast groups

$ns color 10 red

$ns color 11 green

$ns color 30 purple

$ns color 31 green

# Manual layout: order of the link is significant!


#$ns duplex-link-op $n0 $n1 orient right

#$ns duplex-link-op $n0 $n2 orient right-up

#$ns duplex-link-op $n0 $n3 orient right-down

# Show queue on simplex link n0->n1

#$ns duplex-link-op $n2 $n3 queuePos 0.5

# Group 0 source

$udp0 set fid_ 10

$n0 color red

$n0 label "Source 1"

# Group 1 source

$udp1 set fid_ 11

$n1 color green

$n1 label "Source 2"

$n5 label "Receiver 1"

$n5 color blue

$n6 label "Receiver 2"

$n6 color blue

$n7 label "Receiver 3"

$n7 color blue

#$n2 add-mark m0 red

#$n2 delete-mark m0"

# Animation rate

$ns set-animation-rate 3.0ms

$ns run
OUTPUT:
RESULT:

Thus the performance evaluation of routing protocol using simulation tool


(ns2) was executed successfully
EX.NO:10 Simulation of Error Correction Code (Like CRC)
DATE:

AIM:

To write a ‘C’ program to implement Error Detection and Correction


Techniques.

ALGORITHM:

1. Get four bit data

2. Generate the generator matrix

3. Encode the data

4. Create parity check matrix

5. Enter the error data

6. Calculate syndrome using e.HT

7. Decode the error data.


PROGRAM:

#include<stdio.h>

#include<stdlib.h>

char data[5];

int encoded[8],edata[7],syndrome[3];

int hmatrix[3][7] = {

1,0,0,0,1,1,1,

0,1,0,1,0,1,1,

0,0,1,1,1,0,1

};

char gmatrix[4][8]={"0111000","1010100","1100010","1110001"};

int main(){

int i,j;

printf("\nHamming code----- Encoding\n");

printf("Enter 4 bit data : ");

scanf("%s",data);

printf("\nGenerator matrix\n");

for(i=0;i<4;i++)

printf("%s\n",gmatrix[i]);

printf("\nEncoded data ");

for(i=0;i<7;i++)

for(j=0;j<4;j++)
encoded[i]+=((data[j]-'0')*(gmatrix[j][i]-'0'));

encoded[i]=encoded[i]%2;

printf("%d ",encoded[i]);

printf("\nHamming code----- Decoding\n");

printf("Enter encoded bits as recieved : ");

for(i=0;i<7;i++)

scanf("%d",&edata[i]);

for(i=0;i<3;i++)

for(j=0;j<7;j++)

syndrome[i]+=(edata[j]*hmatrix[i][j]);

syndrome[i]=syndrome[i]%2;

for(j=0;j<7;j++)

if((syndrome[0]==hmatrix[0][j]) && (syndrome[1]==hmatrix[1][j])&&

(syndrome[2]==hmatrix[2][j]))

break;

if(j==7)

printf("\nError free\n");

else

printf("\nError recieved at bit number %d of data\n",j+1);

edata[j]=!edata[j];
OUTPUT:

RESULT:

Thus the simulation of error correction code like (CRC) was executed
successfully.

You might also like