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

CN Lab Manual

This document describes a socket programming example using TCP and UDP protocols. It outlines the steps to create a simple date and time client-server application. The server program binds to port 8020, accepts connections, sends the system date/time to clients, and prints received client IP addresses. The client connects to the server, retrieves its own IP address, sends it to the server, and prints the received date/time. Required packages, minimum system requirements, and sample Java code for the server and client programs are provided. The program executes successfully to demonstrate basic socket communication using TCP.

Uploaded by

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

CN Lab Manual

This document describes a socket programming example using TCP and UDP protocols. It outlines the steps to create a simple date and time client-server application. The server program binds to port 8020, accepts connections, sends the system date/time to clients, and prints received client IP addresses. The client connects to the server, retrieves its own IP address, sends it to the server, and prints the received date/time. Required packages, minimum system requirements, and sample Java code for the server and client programs are provided. The program executes successfully to demonstrate basic socket communication using TCP.

Uploaded by

Mohammed Irfan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

THIRUVALLUVAR UNIVERSITY

SERKKADU
VELLORE – 632 115

PG DEPARMENT OF COMPUTER SCIENCE


LAB MANUAL

COMPUTER NETWORKS LAB

PREPARED BY
V.JANANI
DEPARTMENT OF COMPUTER SCIENCE

II SEMESTER – PRACTICAL - V

COMPUTER NETWORKS LAB

I-M.SC CS
2020 – 2021
NAME : ………………………………
REG. NO : ………………………………
SUB.CODE : ………………………………
THIRUVALLUVAR UNIVERSITY

SERKKADU

VELLORE – 32 115

PG DEPARTMENT OF COMPUTER SCIENCE

Certified to be the Bonafide record of the work done by ………………..


Register No. ……………………………………... Of I M.Sc CS during the
academic year 2020 – 2021 in respect of practical under

COMPUTER NETWORKS LAB


II SEMESTER – PRACTICAL - V

Staff – in – charge Head of the Department

V. JANANI, M.C.A., M.Phil., NET., Dr. B. SENTHILKUMAR, M. Sc., Ph.D. M.A (Yoga)

Submitted for the University Practical Examination held on ……………………..


at Thiruvalluvar University, Serkkadu, Vellore – 632 115.

Internal Examiner External Examiner


INDEX

PAGE.
S.NO DATE LIST OF EXPERIMENTS SIGN
NO

NETWORK DEVICES AND


1 COMMANDS
SCOCKET PROGRAM USING TCP
2 AND UDP
CHAT APPLICATION USING
3 SOCKETS

4 HTTP PROTOCOL

SLIDING WINDOW PROTOCOL


5 FOR FLOW CONTROL

6 FILE TRANSFER PROTOCOL

7 ARP/RARP PROTOCOL

A) DISTANCE VECTOR ROUTING


8 B) LINK STATE ROUTING

9 SIMULATOR - WIRED NETWORK

10 SIMULATOR – WIRELESS NETORK


----------------------------------------------------------------------------------------------------
Ex: No: 1 NETWORK DEVICES AND COMMANDS

----------------------------------------------------------------------------------------------------
System administrator:

System administrator, or sysadmin, is a person who is responsible for the upkeep, configuration,
and reliable operation of computer systems; especially multi-user computers, such as servers.The
system administrator seeks to ensure that the uptime, performance, resources, and security of the
computers he or she manages meet the needs of the users, without exceeding the budget.

Skills:

➢ Entails a knowledge of operating systems and applications


➢ Problem solving Technique.
➢ To understand the behaviour of software in order to deploy it and for troubleshooting
problem.

Responsibilities of the System Administrator:


➢ User account management ,
➢ Hardware management
➢ Perform file system backups, restores
➢ Install and configure new software and services
➢ Keep systems and services operating
➢ Monitor system and network ,Troubleshoot problems
➢ Maintain documentation
➢ Audit security ,Help users,

Network administration:

A network administrator, sometimes called a systems administrator, is responsible for keeping an


organization’s computer network up to date and running smoothly. Any company or organization
that uses multiple computers or software platforms needs a network admin to coordinate the
different systems. Network admins will especially be in high demand as companies and
organizations invest in newer, faster technology and mobile networks. Growth is also expected in
the healthcare industry as the use of information technology increases.
Skills of network administrator:
Network admins are responsible for the back end networks, software and hardware as well as for
the teams and end users they support. That means a network admin should have a combination of
problem solving and people skills.
Analysing and critical thinking
Network admins need to explore and solve problems logically and consistently. “The ability to
take the concepts you’ve learned in school and understand how they work and affect other
concepts is the bread and butter of being a network administrator,” says Brad Meyer, systems
administrator at Technology Advice. Even if you don’t yet know the solution, he believes
thinking critically will help you get there. Time management

Network admins juggle several projects, people and problems simultaneously. This means it’s
essential to be organized in the present and looking ahead to prepare for what’s coming next. It’s
like spinning plates with a little practice a network admin can keep everything balanced.
Interpersonal skills
Network admins work with a range of people, from network engineers to help desk employees to
end users, explains Eric Jeffery, founder of IT solutions firm Gungon Consulting. He says
bridging the gap between diverse groups of people requires patience and understanding.
Lifelong learning

The technology field is constantly changing, which means network admins must be willing to
learn and evolve with it. Good network admins are able to adapt to new techniques and
technologies throughout their careers.

Responsibilities of the Network Administrator


As a network administrator, the tasks generally fall into the following areas:
➢Designing and planning the network
➢Setting up the network
➢Maintaining the network
➢Expanding the network

Each task area corresponds to a phase in the continuing life cycle of a network. You might be
responsible for all the phases, or you might ultimately specialize in a particular area, for
example, network maintenance.

Designing the Network:

The first phase in the life cycle of a network involves creating its design, a task not usually
performed by new network administrators. Designing a network involves making decisions
about the type of network that best suits the needs of your organization. In larger sites this task is
performed by a senior network architect: an experienced network administrator familiar with both
network software and hardware.

Setting Up the Network:

After the new network is designed, the second phase of network administration begins, which involves
setting up and configuring the network. This consists of installing the hardware that makes up the
physical part of the network, and configuring the files or databases, hosts, routers, and network
configuration servers. The tasks involved in this phase are a major responsibility for network
administrators. You should expect to perform these tasks unless your organization is very large, with an
adequate network structure already in place.

Maintaining the Network:


The third phase of network administration consists of on-going tasks that typically constitute the bulk of
your responsibilities. They might include:
➢ Adding new host machines to the network
➢ Administering network security
➢ Administering network services, such as NFS services, name services, and electronic mail
➢ Troubleshooting network problems

"Configuring Network Clients" explains how to set up new hosts on an existing network. "General
Troubleshooting Tips" contains hints for solving network problems.

Expanding the Network:

The longer a network is in place and functioning properly, the more your organization might want to
expand its features and services. Initially, you can increase network population by adding new hosts and
expanding network services by providing additional shared software. But eventually, a single network
will expand to the point where it can no longer operate efficiently. That is when it must enter the fourth
phase of the network administration cycle: expansion.

RESULT
The program was executed successfully
----------------------------------------------------------------------------------------------------
Ex: No: 2 SCOCKET PROGRAM USING TCP AND UDP

----------------------------------------------------------------------------------------------------
Algorithm:
Server:
Step1:Create a server socket and bind it to port.
Step 2:Listen for new connection and when a connection arrives, accept it.
Step 3:Send server’s date and time to the client.
Step 4:Read client’s IP address sent by the client.
Step 5:Display the client details.
Step 6:Repeat steps 2-5 until the server is terminated.
Step 7:Close the server socket.
Client
Step1:Create a client socket and connect it to the server’s port number.
Step2:Retrieve its own IP address using built-in function.
Step3:Send its address to the server. Step4:Display
the date & time sent by the server. Step5:Close the
client socket

System and Software tools required:


Package Required : Java Compiler Operating System
: UBUNTU
Minimum Requirement : Pentium III or Pentium IV with 2GB RAM 40 GB hard disk

TCP Program:
dateserver.java
//import java packages
import java.net.*; import java.io.*; importjava.util.*;
/*… Register service on port 8020…*/
ss=new ServerSocket(8020);

/*… Wait and accept a connection…*/


s=ss.accept();
/*… Get a communication stream associated with the socket…*/
ps=new PrintStream(s.getOutputStream());

/* …To get system time…*/ Date


d=new Date(); ps.println(d);
dis=new DataInputStream(s.getInputStream()); inet=dis.readLine();System.out.println("THE
CLIENT SYSTEM ADDRESS IS :"+inet);
/* …This method is used to request for closing or terminating an object…*/
ps.close();}}

dateclient.java

/* …Socket class is having a constructor through this Client program can request to server to get
connection…*/
Socket soc;
DataInputStream dis;
String sdate;
PrintStreamps;

/*…getLocalHost() method: Returns the name of the local computer…*/


InetAddressia=InetAddress.getLocalHost();

/*… Open your connection to a server, at port 8020…*/


soc=new Socket(ia,8020);

/*… Get an input file handle from the socket and read the input…*/

/*…getInputStream()-This method take the permission to write the data from client program to server
program and server program to client program…*/
dis=new DataInputStream(soc.getInputStream());
sdate=dis.readLine();
System.out.println("THE date in the server is:"+sdate);
/* …getOutputStream()-This method is used to take the permission to read data from client system by
the server or from the server system by the client…*/
ps=new PrintStream(soc.getOutputStream());
ps.println(ia);}
UDP Program:
Server.java
/*…import java packages…*/
import java.net.*; import java.io.*; importjava.util.*;
/*..receiving the packet from client…*/
DatagramPacketrp=new DatagramPacket(rd,rd.length); ss.receive(rp);
InetAddress ip= rp.getAddress(); int port=rp.getPort();
/*… getting system time…*/
Date d=new Date();

/*… converting it to String…*/


String time= d + "";

/*… converting that String to byte…*/


sd=time.getBytes();

/*…sending the data to the client…*/


DatagramPacketsp=new DatagramPacket(sd,sd.length,ip,port);
ss.send(sp);

Clientnew.java

/*…send the data to the server(data,length,ip address and port number)…*/


DatagramPacketsp=new DatagramPacket(sd,sd.length,ip,1234);
DatagramPacketrp=new DatagramPacket(rd,rd.length);

/*…To Send the data…*/


cs.send(sp); cs.receive(rp);
String time=new String(rp.getData()); System.out.println(time);

/*…This method is used to request for closing or terminating an object…*/


cs.close(); } }
OUTPUT

UDP Output:

TCP Output

RESULT

The program was executed successfully


----------------------------------------------------------------------------------------------------
Ex: No: 3 CHAT APPLICATION USING SOCKETS

----------------------------------------------------------------------------------------------------
Algorithm:
Server
Step1: Start the program and create server and client sockets.
Step2: Use input streams to get the message from user.
Step3: Use output streams to send message to the client.
Step4: Wait for client to display this message and write a new one to be displayed by the server.
Step5: Display message given at client using input streams read from socket.
Step6: Stop the program.
Client
Step1: Start the program and create a client socket that connects to the required host and port.
Step2: Use input streams read message given by server and print it.
Step3: Use input streams; get the message from user to be given to the server.
Step4: Use output streams to write message to the server.
Step5: Stop the program.

Program
GossipServer.java

ServerSocketsersock = new ServerSocket(3000);


System.out.println("Server ready for chatting");
Socket sock = sersock.accept( );

/*…reading from keyboard (keyRead object)…*/


BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));

/*…sending to client (pwrite object)…*/


OutputStreamostream = sock.getOutputStream();
PrintWriterpwrite = new PrintWriter(ostream, true);
/*… receiving from server ( receiveRead object)…*/
InputStreamistream = sock.getInputStream();
BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));
String receiveMessage, sendMessage;
while(true)
{if((receiveMessage = receiveRead.readLine()) != null)
{System.out.println(receiveMessage); }

GossipClient.java
Socket sock = new Socket("127.0.0.1", 3000);

/*…reading from keyboard (keyRead object)…*/


BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));

/*…sending to client (pwrite object)…*/


OutputStreamostream = sock.getOutputStream();
PrintWriterpwrite = new PrintWriter(ostream, true);

/*… receiving from server ( receiveRead object)…*/


InputStreamistream = sock.getInputStream();
BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));

System.out.println("Start the chitchat, type and press Enter key");


String receiveMessage, sendMessage;
while(true)
{sendMessage = keyRead.readLine(); /*... keyboard reading ...*/
pwrite.println(sendMessage); /*... sending to server...*/
pwrite.flush(); /*... flush the data...*/
if((receiveMessage = receiveRead.readLine()) != null) /*...receive from server...*/
{System.out.println(receiveMessage);} /*... displaying at DOS prompt...*/
OUTPUT

RESULT

The program was executed successfully


----------------------------------------------------------------------------------------------------
Ex: No: 4 HTTP PROTOCOL

----------------------------------------------------------------------------------- --- -- -- --
Algorithm:

Step1: Set a server port as 80.


Step2: Using HTTP services create a Socket for server by specifying the server port
Step3: Use HTTP socket for connecting the client to the URL.
Step4: Use BufferedReader to output stream to place the response from the server by the client.
Step5: Close the Connection as soon the request is been serviced. Use Malformed URL
exception If any errors in grabbing the server

PROGRAM

Client.java

/* …create file object…*/


importjava.io.File;
importjava.io.IOException;

/*…used to perform read and write operation…*/


importjavax.imageio.ImageIO;

public class Client{


public static void main(String args[]) throws Exception{
Socket soc;
BufferedImageimg = null; soc=new
Socket("localhost",4000);
System.out.println("Client is running. "); try
{
System.out.println("Reading image from disk. ");

/*…read image file…*/


img = ImageIO.read(new File("kalpanasonika.jpg"));
ByteArrayOutputStreambaos = new ByteArrayOutputStream();
/*…write image file…*/
ImageIO.write(img, "jpg", baos);
baos.flush();

/*…we use toByteArray() method of ByteArrayOutputStream class…*/


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

Server.java
//…Create Server Socket…//
ServerSocket server=null; Socket
socket;
//…Register Service port to 4000…// server=new
ServerSocket(4000); System.out.println("Server
Waiting for image");
socket=server.accept(); System.out.println("Client connected.");
InputStream in =socket.getInputStream();
DataInputStream dis = new DataInputStream(in);
intlen = dis.readInt();
System.out.println("Image Size: " + len/1024 + "KB"); byte[]
data = new byte[len];
dis.readFully(data);
//…method is used to request for closing or terminating an object…//
dis.close();
in.close();
InputStreamian = new ByteArrayInputStream(data);
BufferedImagebImage = ImageIO.read(ian);
//…create a frame window entitled “server”…//
JFrame f = new JFrame("Server"); ImageIcon
icon = new ImageIcon(bImage);
OUTPUT

RESULT

The program was executed successfully


----------------------------------------------------------------------------------------------------
Ex: No: 5 SLIDING WINDOW PROTOCOL FOR FLOW CONTROL

---------------------------------------------------------------------------------------- -- -- --
Algorithm:

Step1:Create the nodes in the network Step2:Give


the link between the nodes created. Step3:Create a
TCP agent.
Step4:Give the corresponding id for the agents which have been created.
Step5:Attach the created agents to the respective nodes
Step6:Specify the application program which is running on the node
Step7:Set the window size for the TCP nodes
Step8:Give the start and termination time for the application o the run in the network.
Step9:Repeat the above steps for the number of TCP agents necessary for your topology.
Step10:Execute the file using NAM (network animation monitor) and view the output.
PROGRAM
Nodes creation:
set ns [new Simulator]
set tracefile1 [open out.tr w]
$ns trace-all $tracefile1
setnamfile [open out.nam w]
$ns namtrace-all $namfile set
n0 [$ns node]
set n1 [$ns node]

Colouring the node:


$n0 color red
$n1 color red

Giving the link between nodes


$ns duplex-link $n0 $n3 0.5Mb 250ms DropTail
$ns duplex-link $n1 $n3 0.5Mb 250ms DropTail
Creating TCP agents and application
set tcp1 [new Agent/TCP]
$tcp1 set fid_ 1
$ns attach-agent $n0 $tcp1
set sink1 [new Agent/TCPSink]
$ns attach-agent $n7 $sink1 set
ftp [new Application/FTP]
$ftp attach-agent $tcp1
$ns connect $tcp1 $sink1
$tcp1 set window_ 5
$ns at 0.3 "$ftp start"
$ns at 5.0 "$ftp stop"

Executing the code


proc finish {} {
global ns tracefile1 namfile
$ns flush-trace close
$tracefile1 close
$namfile
execnam -a out.nam&
exit 0}$ns at 8.2 "finish"$ns run
OUTPUT

RESULT

The program was executed successfully


----------------------------------------------------------------------------------------------------
Ex: No: 6 FILE TRANSFER PROTOCOL

----------------------------------------------------------------------------------------------------
PROGRAM
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
/**
* A program that demonstrates how to upload files from local computer
* to a remote FTP server using Apache Commons Net API.
* @author www.codejava.net
*/
public class FTPUploadFileDemo {

public static void main(String[] args) {


String server = "www.myserver.com";
int port = 21;
String user = "user";
String pass = "pass";

FTPClient ftpClient = new FTPClient();


try {

ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();

ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

// APPROACH #1: uploads first file using an InputStream


File firstLocalFile = new File("D:/Test/Projects.zip");

String firstRemoteFile = "Projects.zip";


InputStream inputStream = new FileInputStream(firstLocalFile);

System.out.println("Start uploading first file");


boolean done = ftpClient.storeFile(firstRemoteFile, inputStream);
inputStream.close();
if (done) {
System.out.println("The first file is uploaded successfully.");
}
// APPROACH #2: uploads second file using an OutputStream
File secondLocalFile = new File("E:/Test/Report.doc");
String secondRemoteFile = "test/Report.doc";
inputStream = new FileInputStream(secondLocalFile);

System.out.println("Start uploading second file");


OutputStream outputStream = ftpClient.storeFileStream(secondRemoteFile);
byte[] bytesIn = new byte[4096];
int read = 0;

while ((read = inputStream.read(bytesIn)) != -1) {


outputStream.write(bytesIn, 0, read);
}
inputStream.close();
outputStream.close();

boolean completed = ftpClient.completePendingCommand();


if (completed) {
System.out.println("The second file is uploaded successfully.");
}

} catch (IOException ex) {


System.out.println("Error: " + ex.getMessage());
ex.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
OUTPUT
Start uploading first file : File1.txt
The first file is uploaded successfully.

Start uploading second file: File2.txt


The second file is uploaded successfully.

RESULT

The program was executed successfully


----------------------------------------------------------------------------------------------------
Ex: No: 7 ARP/RARP PROTOCOL

----------------------------------------------------------------------------------------------------
ALGORITHM:
Client
1. Start the program
2. Using socket connection is established between client and server.
3. Get the IP address to be converted into MAC address.
4. Send this IP address to server.
5. Server returns the MAC address to client.
Server
1. Start the program
2. Accept the socket which is created by the client.
3. Server maintains the table in which IP and corresponding MAC addresses are stored.
4. Read the IP address which is send by the client.
5. Map the IP address with its MAC address and return the MAC address to client. PROGRAM

Program
Client:
import java.io.*;
import java.net.*;
import java.util.*;
class Clientarp
{
public static void main(String args[])
{
try
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
Socket clsct=new Socket("127.0.0.1",5604);
DataInputStream din=new DataInputStream(clsct.getInputStream());
DataOutputStream dout=new
DataOutputStream(clsct.getOutputStream());
System.out.println("Enter the Logical address(IP):");
String str1=in.readLine();
dout.writeBytes(str1+'\n');
String str=din.readLine();
System.out.println("The Physical Address is: "+str);
clsct.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
}
Server:
import java.io.*;
import
java.net.*;
import
java.util.*;
class Serverarp
{
public static void main(String args[])
{
try
{
ServerSocket obj=new
ServerSocket(5604);
Socket obj1=obj.accept();
while(true)
{
DataInputStream din=new DataInputStream(obj1.getInputStream());
DataOutputStream dout=new
DataOutputStream(obj1.getOutputStream()); String str=din.readLine();
String ip[]={"165.165.80.80","165.165.79.1"};
String mac[]={"6A:08:AA:C2","8A:BC:E3:FA"};
for(int i=0;i<ip.length;i++)
{
if(str.equals(ip[i]))
{
dout.writeBytes(mac[i]+'\n');
break;
}
}
obj.close();
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
OUTPUT
E:\networks>java Serverarp
E:\networks>java Clientarp
Enter the Logical address(IP):
165.165.80.80
The Physical Address is: 6A:08:AA:C2

RESULT

The program was executed successfully


----------------------------------------------------------------------------------------------------
Ex: No: 8 A) DISTANCE VECTOR ROUTING
B) LINK STATE ROUTING
----------------------------------------------------------------------------------------------------
PROGRAM
A) Distance vector Routing
set ns [new Simulator] set nr [open thro.tr w]
$ns trace-all $nr
setnf [open thro.nam w]
$ns namtrace-all $nf proc
finish { }
{global ns nr nf
$ns flush-trace
close $nf close $nr
execnamthro.nam& exit
0}
for { set i 0 }
{ $i < 12}
{ incr i 1 }
{set n($i) [$ns node]} for
{set i 0}
{$i < 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 "$cbr0 start"
$ns at 2.0 "$cbr1 start"
$ns at 45 "finish"
$ns run
OUTPUT

B) Link State Routing


import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Scanner;
import javax.swing.JFileChooser;
public class Dijkstra {
static int Max_rooters;
static int DistGrph[][] = null; //Initialization and Declarations of
variables
static int DistRow[] = null;
static int source = -1,destination = -1;
class ConTableEntry {
boolean flg;
int length;
int []ids;
int depth;
}
static ConTableEntry []conTable = null; //Connection Table initialization
//Main Method
public static void main(String[] args) {
Dijkstra psFrame = new Dijkstra();
}
public int nodeid(int in){
return (in+1);
}
/* ReadTextfileToBuildGraph Method */
public void ReadTextfileToBuildGraph() {
try
{
System.out.println("Enter Text File name to read Network Topology Matrix:");
Scanner in1 = new Scanner(System.in); //Takes from the user the
input file name
String fiename = in1.nextLine();
FileReader fr = new FileReader(fiename); //Creation of FileReader object
String val=new String();
//Creation of BufferedReader Object
BufferedReader br = new BufferedReader(fr);
String[] temp;
val=br.readLine();
temp = val.split(" "); //to find size of the matrics or number of rooters
DistGrph = new int [temp.length][temp.length];
//Close the BufferedReader Object
br.close();
//Close FileReader Object
fr.close();
System.out.println("<=======:Graph Size Read:=======>"+temp.length);
fr = new FileReader(fiename);//Read the content of file into the FileReader
object
val=new String();
//Creation of BufferedReader Object
br = new BufferedReader(fr);
int i = 0;
while((val=br.readLine())!=null)
{
String[] temp1;
temp1 = val.split(" "); //Splitting with space as a Delimiter
for (int dist =0; dist < temp1.length; dist++ ){
DistGrph[i][dist] = Integer.parseInt(temp1[dist]);
}
i++;
}
//Close the BufferedReader Object
br.close();
//Close FileReader Object
fr.close();
System.out.println("<=======:Graph Table Initialized:=======>");
Max_rooters = i;
String imageName = "%3d" ; //Formatting to display the Content in the
Matrix format
System.out.println();
System.out.print("ID|");
for (int j =0; j < Max_rooters; j++ ){
System.out.print(String.format( imageName,nodeid(j)));
}
System.out.println();
System.out.println("-------------------------------------------------------------------");
for (int j =0; j < Max_rooters; j++ ){
imageName = "%2d|" ; //Formatting to display the Content in the Matrix
format
System.out.print(String.format( imageName,nodeid(j)));
imageName = "%3d" ;
for (int k =0; k < Max_rooters; k++ )
System.out.print( String.format( imageName, DistGrph[j][k]));
//System.out.print(" "+DistGrph[j][k] +" ");
System.out.println();
}
System.out.println("-------------------------------------------------------------------");
//}
} catch(Exception e){
//e.printStackTrace();
System.out.println("File Not Found, Please Enter a Valid File !"); //To
Handle File Not Found Exception
}
}

OUTPUT

RESULT:
Thus the program was successfully executed.
----------------------------------------------------------------------------------------------------
Ex: No: 9 SIMULATOR - WIRED NETWORK
----------------------------------------------------------------------------------------------------

Ethernet is a LAN (Local area Network) protocol operating at the MAC (Medium Access Control)
layer. Ethernet has been standardized as per IEEE 802.3. The underlying protocol in Ethernet is known as
the CSMA / CD – Carrier Sense Multiple Access / Collision Detection. The working of the Ethernet
protocol is as explained below, A node which has data to transmit senses the channel. If the channel is idle
then, the data is transmitted. If the channel is busy then, the station defers transmission until the channel is
sensed to be idle and then immediately transmitted. If more than one node starts data transmission at the
same time, the data collides. This collision is heard by the transmitting nodes which enter into contention
phase. The contending nodes resolve contention using an algorithm called Truncated binary exponential
back off.
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 six nodes that forms a network numbered from 0 to 5
5. Create duplex links between the nodes and add Orientation to the nodes for setting a
LANtopology
6. Setup TCP Connection between n(0) and n(4)
7. Apply FTP Traffic over TCP
8. Setup UDP Connection between n(1) and n(5)
9. Apply CBR Traffic over UDP.
10. Apply CSMA/CA and CSMA/CD mechanisms and study their performance
11. Schedule events and run the program.

PROGRAM
CSMA/CA
set ns [new Simulator]
#Define different colors for data flows (for NAM)
$ns color 1 Blue
$ns color 2 Red #Open the Trace files
set file1 [open out.tr w]
set winfile [open WinFile 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 0
}
#Create six 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]
$n1 color red
$n1 shape box
#Create links between the nodes
$ns duplex-link $n0 $n2 2Mb 10ms DropTail
$ns duplex-link $n1 $n2 2Mb 10ms DropTail
$ns simplex-link $n2 $n3 0.3Mb 100ms DropTail
$ns simplex-link $n3 $n2 0.3Mb 100ms DropTail
set lan [$ns newLan "$n3 $n4 $n5" 0.5Mb 40ms LL Queue/DropTail MAC/Csma/Ca
Channel]
Setup a TCP connection
set tcp [new Agent/TCP/Newreno]
$ns attach-agent $n0 $tcp
set sink [new Agent/TCPSink/DelAck]
$ns attach-agent $n4 $sink
$ns connect $tcp $sink
$tcp set fid_ 1
$tcp set window_ 8000
$tcp set packetSize_ 552
#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 $n5 $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_ 0.01mb
$cbr set random_ false
$ns at 0.1 "$cbr start"
$ns at 1.0 "$ftp start"
$ns at 124.0 "$ftp stop"
$ns at 124.5 "$cbr stop"
# next procedure gets two arguments: the name of the # tcp source node, will be called here
"tcp",
# and the name of output file.
proc plotWindow {tcpSource file} { global ns
set time 0.1
set now [$ns now]
set cwnd [$tcpSource set cwnd_] set wnd [$tcpSource set window_] puts $file "$now $cwnd"
$ns at [expr $now+$time] "plotWindow $tcpSource $file" }
$ns at 0.1 "plotWindow $tcp $winfile"
$ns at 5 "$ns trace-annotate \"packet drop\"" # PPP
$ns at 125.0 "finish"
$ns run
OUTPUT

RESULT

The program was executed successfully


----------------------------------------------------------------------------------------------------
Ex: No: 10 SIMULATOR – WIRELESS NETORK
----------------------------------------------------------------------------------------------------

A mobile ad hoc network or MANET does not depend on a fixed infrastructure for its
networkingoperation. MANET is an autonomous and short-lived association of group of mobile
nodes that communicate with each other over wireless links. A node can directly communicate to
the nodes that lie within its communication range. If a node wants to communicate with a node
that is not directly within its communication range, it uses intermediate nodes as routers.
ALGORITHM:
1. Create a simulator object
2. Set the values for the parameter
3. Open a nam trace file and define finish procedure then close the trace file, and execute nam on trace
file.
4. Create the nodes that forms a network numbered from 0 to 3
5. Schedule events and run the program.
PROGRAM
set val(chan) Channel/WirelessChannel
set val(prop) Propagation/TwoRayGround
set val(netif) Phy/WirelessPhy
set val(mac) Mac/802_11
set val(ifq) Queue/DropTail/PriQueue
set val(ll) LL
set val(ant) Antenna/OmniAntenna
set val(ifqlen) 50
set val(nn) 3
set val(rp) DSDV
set ns [new Simulator]
set tf [open output.tr w]
$ns trace-all $tf
set tf1 [open output.nam w]
$ns namtrace-all-wireless $tf1 100 100
set topo [new Topography]
$topo load_flatgrid 100 100
create-god $val(nn)
$ns node-config -adhocRouting $val(rp) \
-llType $val(ll) \
-macType $val(mac) \
-ifqType $val(ifq) \
-ifqLen $val(ifqlen) \
-antType $val(ant) \
-propType $val(prop) \
-phyType $val(netif) \
-channelType $val(chan) \
-topoInstance $topo \
-agentTrace ON \
-routerTrace OFF \
-macTrace OFF \
-movementTrace OFF
set node0 [$ns node]
set node1 [$ns node]
set node2 [$ns node]
$ns initial_node_pos $node0 10
$ns initial_node_pos $node1 10
$ns initial_node_pos $node2 10
$node0 set X_ 25.0
$node0 set Y_ 50.0
$node0 set Z_ 0.0
$node1 set X_ 50.0
$node1 set Y_ 50.0
$node1 set Z_ 0.0
$node2 set X_ 65.0
$node2 set Y_ 50.0
$node2 set Z_ 0.0
set tcp1 [new Agent/TCP]
$ns attach-agent $node0 $tcp1
set ftp [new Application/FTP]
$ftp attach-agent $tcp1
set sink1 [new Agent/TCPSink]
$ns attach-agent $node2 $sink1
$ns connect $tcp1 $sink1
$ns at 10.0 "$node1 setdest 50.0 90.0 0.0"
$ns at 50.0 "$node1 setdest 50.0 10.0 0.0"
$ns at 0.5 "$ftp start"
$ns at 1000 "$ftp stop"
$ns at 1000 "finish"
proc finish {} {
global ns tf tf1
$ns flush-trace
close $tf
exec nam output.nam &
exit 0
}
$ns run
OUTPUT

RESULT

The program was executed successfully.

You might also like