Вы находитесь на странице: 1из 58

1

HINDUSTHAN COLLEGE OF ENGINEERING AND TECHNOLOGY

COIMBATORE - 32

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

CS 6411 / NETWORKS LABORATORY

NAME :

REGISTER NO :

CLASS :
2

HINDUSTHAN COLLEGE OF ENGINEERING AND TECHNOLOGY

COIMBATORE 32

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


Certify that this is the bonafide record of work done by

_____________________________________________

in the CS 6411 Networks Laboratory

of this institution, as prescribed by the Anna University, Chennai

for the Fourth semester during the year 2016-2017.

Place: COIMBATORE

Date:

Staff in-Charge Head of the Department

University Register No: _____________________________

Submitted for the practical examination of the Anna University conducted on ____________

Internal Examiner External Examiner


3

CS 6411 NETWORKS LABORATORY


INDEX
EX. PAGE
DATE NAME OF THE EXPERIMENT MARKS STAFF SIGN
NO. NO.
Implementation of Stop and Wait Protocol and Sliding
1
Window Protocol

2 Study of Socket Programming and Client-Server model

3 Implementation of simulation of ARP/RARP protocols

Implementation of simulation of PING and


4
TRACEROUTE commands
Implementation of socket creation for HTTP for web
5
page upload and download

6 Implementation of RPC (Remote Procedure Call)

7 Implementation of Subnetting

Implementation TCP socket applications Echo client and


8
echo server, Chat and File Transfer
Implementation of TCP and UDP sockets applications
9
DNS, SNMP and File Transfer
Study of Network Simulator and simulation of
10
congestion Control Algorithms using NS
Case study of Routing Algorithms Link State Routing,
11
Flooding and Distant Vector Routing

12 Implementation of CSMA/CD using Network Simulator

AVERAGE MARKS

Staff - In charge
Ex.No:1 Implementation of Stop and Wait Protocol and Sliding Window Protocol
4

AIM
To implement Stop and Wait Protocol and Sliding Window Protocol using Java.
STOP AND WAIT PROTOCOL
ALGORITHM
Step 1: Start.
Step 2 : Invoke the classes ObjectOutputStream and ObjectInputStream with an object to get the input and to
project the output between the sender and receiver
Step 3: Create the socket class for both sender and receiver
Step 4: Split the messages sent from the sender and write on the receiver using writeobj
Step 5: the packets are created by partitioning the messages
Step 6: Terminate the program
PROGRAM
Sender:
import java.io.*;
import java.net.*;
public class Sender{
Socket sender;
ObjectOutputStream out;
ObjectInputStream in;
String packet,ack,str, msg;
int n,i=0,sequence=0;
Sender(){}
public void run(){
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Waiting for Connection....");
sender = new Socket("localhost",2004);
sequence=0;

out=new ObjectOutputStream(sender.getOutputStream());
out.flush();
in=new ObjectInputStream(sender.getInputStream());
str=(String)in.readObject();
System.out.println("receiver > "+str);
System.out.println("Enter the data to send....");
packet=br.readLine();
n=packet.length();
do{
try{
if(i<n){
msg=String.valueOf(sequence);
msg=msg.concat(packet.substring(i,i+1));
}
else if(i==n){
msg="end";out.writeObject(msg);break;
}
out.writeObject(msg);
sequence=(sequence==0)?1:0;
out.flush();
5

System.out.println("data sent>"+msg);
ack=(String)in.readObject();
System.out.println("waiting for ack.....\n\n");
if(ack.equals(String.valueOf(sequence))){
i++;
System.out.println("receiver > "+" packet recieved\n\n");
}
else{
System.out.println("Time out resending data....\n\n");
sequence=(sequence==0)?1:0;
}
}catch(Exception e){}
}while(i<n+1);
System.out.println("All data sent. exiting.");
}catch(Exception e){}
finally{
try{
in.close();
out.close();
sender.close();
}
catch(Exception e){}
}
}
public static void main(String args[]){
Sender s=new Sender();
s.run();
}
}
Receiver:
import java.io.*;
import java.net.*;
public class Receiver{
ServerSocket reciever;
Socket connection=null;
ObjectOutputStream out;
ObjectInputStream in;
String packet,ack,data="";
int i=0,sequence=0;
Reciever(){}
public void run(){
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
reciever = new ServerSocket(2004,10);
System.out.println("waiting for connection...");
connection=reciever.accept();
sequence=0;
System.out.println("Connection established :");
out=new ObjectOutputStream(connection.getOutputStream());
out.flush();
in=new ObjectInputStream(connection.getInputStream());
6

out.writeObject("connected .");
do{
try{
packet=(String)in.readObject();
if(Integer.valueOf(packet.substring(0,1))==sequence){
data+=packet.substring(1);
sequence=(sequence==0)?1:0;
System.out.println("\n\nreceiver >"+packet);
}
else
{
System.out.println("\n\nreceiver>"+packet +" duplicate data");
}
if(i<3){
out.writeObject(String.valueOf(sequence));i++;
}
else{
out.writeObject(String.valueOf((sequence+1)%2));
i=0;
}
}
catch(Exception e){}
}while(!packet.equals("end"));
System.out.println("Data recived="+data);
out.writeObject("connection ended .");
}
catch(Exception e){}
finally{
try{
in.close();
out.close();
reciever.close();
}
catch(Exception e){}
}
}
public static void main(String args[]){
Reciever s=new Reciever();
while(true){
s.run();
}}}
OUTPUT
Sender:
Waiting for Connection....
reciver > connected .
Enter the data to send....
myname
data sent>0m
waiting for ack.....
receiver > packet recieved
7

data sent>1y
waiting for ack.....
receiver > packet recieved
data sent>0n
waiting for ack.....
receiver > packet recieved
data sent>1a
waiting for ack.....
Time out resending data....
data sent>1a
waiting for ack.....
receiver > packet recieved
data sent>0m
waiting for ack.....
receiver > packet recieved
data sent>1e
waiting for ack.....
receiver > packet recieved
All data sent. exiting.
Receiver:
waiting for connection...
Connection established :
receiver >0m
receiver >1y
receiver >0n
receiver >1a
receiver >1a duplicate data
receiver >0m
receiver >1e
Data recived=myname
waiting for connection...
SLIDING WINDOW PROTOCOL
ALGORITHM
Step 1:Start the program.
Step 2:Get the frame size from the user
Step 3:To create the frame based on the user request.
Step 4:To send frames to server from the client side.
Step 5:If your frames reach the server it will send ACK signal to client otherwise it will send NACK signal to
client.
Step 6:Stop the program
PROGRAM
Sender:
import java.net.*;
import java.io.*;
import java.rmi.*;
public class slidsender
{
8

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


{
ServerSocket ser=new ServerSocket(10);
Socket s=ser.accept();
DataInputStream in=new DataInputStream(System.in);
DataInputStream in1=new DataInputStream(s.getInputStream());
String sbuff[]=new String[8];
PrintStream p;
int sptr=0,sws=8,nf,ano,i;
String ch;
do
{
p=new PrintStream(s.getOutputStream());
System.out.print("Enter the no. of frames : ");
nf=Integer.parseInt(in.readLine());
p.println(nf);
if(nf<=sws-1)
{
System.out.println("Enter "+nf+" Messages to be send\n");
for(i=1;i<=nf;i++)
{
sbuff[sptr]=in.readLine();
p.println(sbuff[sptr]);
sptr=++sptr%8;
}
sws-=nf;
System.out.print("Acknowledgment received");
ano=Integer.parseInt(in1.readLine());
System.out.println(" for "+ano+" frames");
sws+=nf;
}
else
{
System.out.println("The no. of frames exceeds window size");
break;
}
System.out.print("\nDo you wants to send some more frames : ");
ch=in.readLine(); p.println(ch);
}
while(ch.equals("yes"));
s.close();
}
}
Receiver:
import java.net.*;
import java.io.*;
class slidreceiver
{
public static void main(String a[])throws Exception
{
Socket s=new Socket(InetAddress.getLocalHost(),10);
9

DataInputStream in=new DataInputStream(s.getInputStream());


PrintStream p=new PrintStream(s.getOutputStream());
int i=0,rptr=-1,nf,rws=8;
String rbuf[]=new String[8];
String ch; System.out.println();
do
{
nf=Integer.parseInt(in.readLine());
if(nf<=rws-1)
{
for(i=1;i<=nf;i++)
{
rptr=++rptr%8;
rbuf[rptr]=in.readLine();
System.out.println("The received Frame " +rptr+" is : "+rbuf[rptr]);
}
rws-=nf;
System.out.println("\nAcknowledgment sent\n");
p.println(rptr+1); rws+=nf; }
else
break;
ch=in.readLine();
}
while(ch.equals("yes"));
}
}
OUTPUT
Sender:
Enter the no. of frames : 4
Enter 4 Messages to be send
hi
how r u
i am fine
how is evryone
Acknowledgment received for 4 frames
Do you wants to send some more frames : no
Receiver:
The received Frame 0 is : hi
The received Frame 1 is : how r u
The received Frame 2 is : i am fine
The received Frame 3 is : how is everyone
RESULT
Thus the java program for implementing stop & wait and sliding window protocol is created and executed.
Ex.No:2
Study of Socket Programming and Client-Server model

AIM
To study about Socket Programming and Client Server model.
SOCKET PROGRAMMING
Sockets provide the communication mechanism between two computers using TCP. A client program creates
a socket on its end of the communication and attempts to connect that socket to a server.
10

When the connection is made, the server creates a socket object on its end of the communication. The client
and server can now communicate by writing to and reading from the socket.
The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a mechanism for
the server program to listen for clients and establish connections with them.
The following steps occur when establishing a TCP connection between two computers using sockets:
The server instantiates a ServerSocket object, denoting which port number communication is to occur
on.
The server invokes the accept() method of the ServerSocket class. This method waits until a client
connects to the server on the given port.
After the server is waiting, a client instantiates a Socket object, specifying the server name and port
number to connect to.
The constructor of the Socket class attempts to connect the client to the specified server and port
number. If communication is established, the client now has a Socket object capable of
communicating with the server.
On the server side, the accept() method returns a reference to a new socket on the server that is
connected to the client's socket.
After the connections are established, communication can occur using I/O streams. Each socket has both an
OutputStream and an InputStream. The client's OutputStream is connected to the server's InputStream, and
the client's InputStream is connected to the server's OutputStream.
TCP is a twoway communication protocol, so data can be sent across both streams at the same time. There are
following usefull classes providing complete set of methods to implement sockets.
ServerSocket Class Methods:
The java.net.ServerSocket class is used by server applications to obtain a port and listen for client requests
The ServerSocket class has four constructors:
public ServerSocket(int port) throws IOException-Attempts to create a server socket bound to the
specified port. An exception occurs if the port is already bound by another application.
public ServerSocket(int port, int backlog) throws IOException-Similar to the previous constructor, the
backlog parameter specifies how many incoming clients to store in a wait queue.
public ServerSocket(int port, int backlog, InetAddress address) throws IOException-Similar to the
previous constructor, the InetAddress parameter specifies the local IP address to bind to. The
InetAddress is used for servers that may have multiple IP addresses, allowing the server to specify
which of its IP addresses to accept client requests on
public ServerSocket() throws IOException-Creates an unbound server socket. When using this
constructor, use the bind() method when you are ready to bind the server socket
If the ServerSocket constructor does not throw an exception, it means that your application has
successfully bound to the specified port and is ready for client requests.
Here are some of the common methods of the ServerSocket class:
public int getLocalPort()- Returns the port that the server socket is listening on. This method
is useful if you passed in 0 as the port number in a constructor and let the server find a port
for you.
Public Socket accept() throws IOException- Waits for an incoming client. This method
blocks until either a client connects to the server on the specified port or the socket times out,
assuming that the time-out value has been set using the setSoTimeout() method. Otherwise,
this method blocks indefinitely
public void setSoTimeout(int timeout)- Sets the time-out value for how long the server socket
waits for a client during the accept().
public void bind(SocketAddress host, int backlog)- Binds the socket to the specified server
and port in the SocketAddress object. Use this method if you instantiated the ServerSocket
using the no-argument constructor.
11

When the ServerSocket invokes accept(), the method does not return until a client connects. After a client
does connect, the ServerSocket creates a new Socket on an unspecified port and returns a reference to this
new Socket. A TCP connection now exists between the client and server, and communication can begin.
Socket Class Methods:
The java.net.Socket class represents the socket that both the client and server use to communicate with each
other. The client obtains a Socket object by instantiating one, whereas the server obtains a Socket object from
the return value of the accept() method.
The Socket class has five constructors that a client uses to connect to a server:
public Socket(String host, int port) throws UnknownHostException, IOException
public Socket(InetAddress host, int port) throws IOException
public Socket(String host, int port, InetAddress localAddress, int localPort) throws IOException
public Socket(InetAddress host, int port, InetAddress localAddress, int localPort) throws IOException
public Socket()
When the Socket constructor returns, it does not simply instantiate a Socket object but it actually
attempts to connect to the specified server and port.
Some methods of interest in the Socket class are listed here. Notice that both the client and server
have a Socket object, so these methods can be invoked by both the client and server.
public void connect(SocketAddress host, int timeout) throws IOException-connects the socket to the
specified host.
public InetAddress getInetAddress()- returns the address of the other computer that this socket is
connected to.
public int getPort()-Returns the port the socket is bound to on the remote machine.
public int getLocalPort()-Returns the port the socket is bound to on the local machine.
public SocketAddress getRemoteSocketAddress()-Returns the address of the remote socket.
public InputStream getInputStream() throws IOException- Returns the input stream of the socket.
public OutputStream getOutputStream() throws IOException-Returns the output stream of the socket.
public void close() throws IOException-Closes the socket
InetAddress Class Methods:
This class represents an Internet Protocol (IP) address. Here are following usefull methods which you would
need while doing socket programming:
static InetAddress getByAddress(byte[] addr)
static InetAddress getByAddress(String host, byte[] addr)
static InetAddress getByName(String host)
String getHostAddress()
String getHostName()
static InetAddress InetAddress getLocalHost()
String toString()

CLIENT SERVER MODEL


The client-server model is a distributed communication framework of network processes among service
requestors, clients and service providers. The client-server connection is established through a network or the
Internet.
The client-server model is a core network computing concept also building functionality for email exchange
and Web/database access. Web technologies and protocols built around the client-server model are:
Hypertext Transfer Protocol (HTTP)
Domain Name System (DNS)
Simple Mail Transfer Protocol (SMTP)
12

Telnet
Clients include Web browsers, chat applications, and email software, among others. Servers include Web,
database, application, chat and email, etc.
A server manages most processes and stores all data. A client requests specified data or processes. The server
relays process output to the client. Clients sometimes handle processing, but require server data resources for
completion.
Computer running a program that makes a request for services is called client machine. A computer running a
program that offers requested services from one or more clients is called server machine. The media for
communication can be wired or wireless network.

Programs running on client machines make requests to a program (often called as server program) running on
a server machine. They involve networking services provided by the transport layer, which is part of the
Internet software stack, often called TCP/IP (Transport Control Protocol/Internet Protocol) stack.
The transport layer comprises two types of protocols,
TCP (Transport Control Protocol) and
UDP (User Datagram Protocol).
The most widely used programming interfaces for these protocols are sockets.
TCP is a connection-oriented protocol that provides a reliable flow of data between two computers. Example
applications that use such services are HTTP, FTP, and Telnet.
UDP is a protocol that sends independent packets of data, called datagrams, from one computer to another
with no guarantees about arrival and sequencing. Example applications that use such services include Clock
server and Ping.
The TCP and UDP protocols use ports to map incoming data to a particular process running on a computer.
Port is represented by a positive (16-bit) integer value.

Hosts Identification and Service Ports


13

Every computer on the Internet is identified by a unique, 4-byte IP address. This is typically written in dotted
quad format like 128.250.25.158 where each byte is an unsigned value between 0 and 255. This
representation is clearly not user-friendly because it does not tell us anything about the content and then it is
difficult to remember. Hence, IP addresses are mapped to names like www.google.com, which are easier to
remember. Internet supports name servers that translate these names to IP addresses
Sockets and Socket-based Communication
Sockets provide an interface for programming networks at the transport layer. Network communication using
Sockets is very much similar to performing file I/O. In fact, socket handle is treated like file handle.
The streams used in file I/O operation are also applicable to socket-based I/O.
Socket-based communication is independent of a programming language used for implementing it. That
means, a socket program written in Java language can communicate to a program written in non-Java (say C
or C++) socket program.
A server (program) runs on a specific computer and has a socket that is bound to a specific port. The server
listens to the socket for a client to make a connection request. If everything goes well, the server accepts the
connection. Upon acceptance, the server gets a new socket bound to a different port. It needs a new socket
(consequently a different port number) so that it can continue to listen to the original socket for connection
requests while serving the connected client

RESULT
Thus the Socket Programming and Client Server model is clearly analyzed and studied
Ex.No:3
Implementation of simulation of ARP/RARP protocols

AIM
To write a java program for simulating ARP/RARP protocols
ADDRESS RESOLUTION PROTOCOL
ALGORITHM
Step 1: 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 servers date and time to the client.
Step 4: Read clients 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: Create a client socket and connect it to the servers port number.
14

Step 8: Retrieve its own physical address using built-in function.


Step 9: Send its address to the server.
Step 10: Display the date & time sent by the server.
Step 11: Close the input and output streams.
Step 12: Close the client socket.
Step 13: Stop.
PROGRAM
Client:
import java.io.*;
import java.net.*;
import java.util.*;
class Clientarp
{
public static void main(String args[])
{
try {
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
Socket clsct=new Socket("127.0.0.1",139);
DataInputStream din=new DataInputStream(clsct.getInputStream());
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(139);
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"};
15

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
Enter the Logical address(IP):
165.165.80.80
The Physical Address is: 6A:08:AA:C2
REVERSE ADDRESS RESOLUTION PROTOCOL
ALGORITHM
Step 1: 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 servers date and time to the client.
Step 4: Read clients physical address sent by the client.
Step 5: Display the client details.
Step 6: Repeat steps 2-5 until the server is terminated.
Step 7: Create a client socket and connect it to the servers port number.
Step 8: Retrieve its IP address using built-in function.
Step 9: Send its address to the server.
Step 10: Display the date & time sent by the server.
Step 11: Close the input and output streams.
Step 12: Close the client socket.
Step 13: Stop.
PROGRAM
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];
16

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


System.out.println("Enter the Physical address (MAC):");
String str=in.readLine();
sendbyte=str.getBytes();
DatagramPacket sender=new DatagramPacket(sendbyte,sendbyte.length,addr,1309);
client.send(sender);
DatagramPacket receiver=new DatagramPacket(receivebyte,receivebyte.length);
client.receive(receiver);
String s=new String(receiver.getData());
System.out.println("The Logical Address is(IP): "+s.trim());
client.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Server:
import java.io.*;
import java.net.*;
import java.util.*;
class Serverrarp12
{
public static void main(String args[])
{
try
{
DatagramSocket server=new DatagramSocket(1309);
while(true)
{
byte[] sendbyte=new byte[1024];
byte[] receivebyte=new byte[1024];
DatagramPacket receiver=new DatagramPacket(receivebyte,receivebyte.length);
server.receive(receiver);
String str=new String(receiver.getData());
String s=str.trim();
InetAddress addr=receiver.getAddress();
int port=receiver.getPort();
String ip[]={"165.165.80.80","165.165.79.1"};
String mac[]={"6A:08:AA:C2","8A:BC:E3:FA"};
for(int i=0;i<ip.length;i++)
{
if(s.equals(mac[i]))
{
sendbyte=ip[i].getBytes();
DatagramPacket sender=new DatagramPacket(sendbyte,sendbyte.length,addr,port);
server.send(sender);
break;
}
}
17

break;
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
OUTPUT
Enter the Physical address (MAC):
6A:08:AA:C2
The Logical Address is(IP): 165.165.80.80

RESULT
Thus the program for simulating ARP/RARP protocols has been created and the outputs have been verified.
Ex.No:4
Implementation of simulation of PING and TRACEROUTE commands

Aim
To implement the simulation of PING and TRACEROUTE commands using Java.
PING
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 BufferedReader 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
Client:
import java.io.*;
import java.net.*;
18

import java.util.Calendar;
class pingclient
{
public static void main(String args[])throws Exception
{
String str;
int c=0;
long t1,t2;
Socket s=new Socket("127.0.0.1",5555);
DataInputStream dis=new DataInputStream(s.getInputStream());
PrintStream out=new PrintStream(s.getOutputStream());
while(c<4)
{
t1=System.currentTimeMillis();
str="Welcome to network programming world";
out.println(str);
System.out.println(dis.readLine());
t2=System.currentTimeMillis();
System.out.println(";TTL="+(t2-t1)+"ms");
c++;
}
s.close(); }
}
Server:
import java.io.*;
import java.net.*;
import java.util.*;
import java.text.*;
class pingserver
{
public static void main(String args[])throws Exception
{
ServerSocket ss=new ServerSocket(5555);
Socket s=ss.accept();
int c=0;
while(c<4)
{
DataInputStream dis=new DataInputStream(s.getInputStream());
PrintStream out=new PrintStream(s.getOutputStream());
String str=dis.readLine();
out.println("Reply from"+InetAddress.getLocalHost()+";Length"+str.length());
c++;
}
s.close();
}
}
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
19

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
TRACEROUTE
ALGORITHM
Step 1: Start the program.
Step 2: Include necessary package in java
Step 3: Make the traces on certain addresses
Step 4: Uses Runtime class and its associated functions
Step 5: Stop
PROGRAM
import java.io.*;
import java.net.*;
class TraceServer
{
public static void main(String args[])
{
try
{
String str;
System.out.print(" Enter the IP Address to be Traced : ");
BufferedReader buf1=new BufferedReader(new InputStreamReader(System.in));
String ip=buf1.readLine();
Runtime H=Runtime.getRuntime();
Process p=H.exec("tracert " + ip);
InputStream in=p.getInputStream();
BufferedReader buf2=new BufferedReader(new
InputStreamReader(in));
while((str=buf2.readLine())!=null)
{
System.out.println(" " + str);
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
OUTPUT
D:\networks>javac TraceServer.java
D:\networks>java TraceServer
Enter the IP Address to be Traced : 172.20.1.20
Tracing route to hcet [172.20.1.20]
over a maximum of 30 hops:
1 1 ms <1 ms <1 ms hcet [172.20.1.20]
Trace complete.
20

RESULT
Thus the implementation for PING and TRACEROUTE has been done and verified successfully.
Ex.No:5
Implementation of socket creation for HTTP for web page upload and download

AIM
To implement socket creation for HTTP for web page upload and download using Java
ALGORITHM
Step 1: Start.
Step 2: Import http web oriented packages.
Step 3: Give the sample html tags for starting page with title
Step 4: Create the objects for the classes socket, BufferedReader and DataOutputStream
Step 5: Get the internet address and port using the Inetaddress and port functions
Step 6: GET and POST methods are used to download and upload the contents
Step 7: Terminate the program
PROGRAM
import java.io.*;
import java.net.*;
import java.util.*;
public class myHTTPServer extends Thread {
static final String HTML_START =
"<html>" +
"<title>HTTP Server in java</title>" +
"<body>";
static final String HTML_END =
"</body>" +
"</html>";
Socket connectedClient = null;
BufferedReader inFromClient = null;
21

DataOutputStream outToClient = null;


public myHTTPServer(Socket client) {
connectedClient = client;
}
public void run() {
try {
System.out.println( "The Client "+
connectedClient.getInetAddress() + ":" + connectedClient.getPort() + " is connected");
inFromClient = new BufferedReader(new InputStreamReader (connectedClient.getInputStream()));
outToClient = new DataOutputStream(connectedClient.getOutputStream());
String requestString = inFromClient.readLine();
String headerLine = requestString;
StringTokenizer tokenizer = new StringTokenizer(headerLine);
String httpMethod = tokenizer.nextToken();
String httpQueryString = tokenizer.nextToken();
StringBuffer responseBuffer = new StringBuffer();
responseBuffer.append("<b> This is the HTTP Server Home Page.... </b><BR>");
responseBuffer.append("The HTTP Client request is ....<BR>");
System.out.println("The HTTP request string is ....");
while (inFromClient.ready())
{
// Read the HTTP complete HTTP Query
responseBuffer.append(requestString + "<BR>");
System.out.println(requestString);
requestString = inFromClient.readLine();
}
if (httpMethod.equals("GET")) {
if (httpQueryString.equals("/")) {
// The default home page
sendResponse(200, responseBuffer.toString(), false);
} else {
//This is interpreted as a file name
String fileName = httpQueryString.replaceFirst("/", "");
fileName = URLDecoder.decode(fileName);
if (new File(fileName).isFile()){
sendResponse(200, fileName, true);
}
else {
sendResponse(404, "<b>The Requested resource not found ...." +
"Usage: http://127.0.0.1:5000 or http://127.0.0.1:5000/</b>", false);
}
}
}
else sendResponse(404, "<b>The Requested resource not found ...." +
"Usage: http://127.0.0.1:5000 or http://127.0.0.1:5000/</b>", false);
} catch (Exception e) {
e.printStackTrace();
}
}
public void sendResponse (int statusCode, String responseString, boolean isFile) throws Exception {
String statusLine = null;
22

String serverdetails = "Server: Java HTTPServer";


String contentLengthLine = null;
String fileName = null;
String contentTypeLine = "Content-Type: text/html" + "\r\n";
FileInputStream fin = null;
if (statusCode == 200)
statusLine = "HTTP/1.1 200 OK" + "\r\n";
else
statusLine = "HTTP/1.1 404 Not Found" + "\r\n";
if (isFile) {
fileName = responseString;
fin = new FileInputStream(fileName);
contentLengthLine = "Content-Length: " + Integer.toString(fin.available()) + "\r\n";
if (!fileName.endsWith(".htm") && !fileName.endsWith(".html"))
contentTypeLine = "Content-Type: \r\n";
}
else {
responseString = myHTTPServer.HTML_START + responseString + myHTTPServer.HTML_END;
contentLengthLine = "Content-Length: " + responseString.length() + "\r\n";
}
outToClient.writeBytes(statusLine);
outToClient.writeBytes(serverdetails);
outToClient.writeBytes(contentTypeLine);
outToClient.writeBytes(contentLengthLine);
outToClient.writeBytes("Connection: close\r\n");
outToClient.writeBytes("\r\n");
if (isFile) sendFile(fin, outToClient);
else outToClient.writeBytes(responseString);
outToClient.close();
}
public void sendFile (FileInputStream fin, DataOutputStream out) throws Exception {
byte[] buffer = new byte[1024] ;
int bytesRead;
while ((bytesRead = fin.read(buffer)) != -1 ) {
out.write(buffer, 0, bytesRead);
}
fin.close();
}
public static void main (String args[]) throws Exception {

ServerSocket Server = new ServerSocket (5000, 10, InetAddress.getByName("127.0.0.1"));


System.out.println ("TCPServer Waiting for client on port 5000");
while(true) {
Socket connected = Server.accept();
(new myHTTPServer(connected)).start();
}
}
}
OUTPUT
1. http://127.0.0.1:5000 should print the home page with the HTTP request parameters
This is the HTTP Server Home Page....
23

The HTTP Client request is ....


GET / HTTP/1.1
Host: 127.0.0.1:5000
User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:43.0) Gecko/20100101 Firefox/43.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
2. http://127.0.0.1:5000/myHTTPServer.java would download the java source file, provided you run the
java class file in the same location or try any other file in the file system by giving the absolute path that
would be downloaded.
3. http://127.0.0.1:5000/invalidfile would result in HTTP 404 file not found error.
The Requested resource not found ....Usage: http://127.0.0.1:5000 or http://127.0.0.1:5000/

RESULT
Thus the program is done for web page upload download and the output has been verified.
Ex.No:6
Implementation of RPC (Remote Procedure Call)

AIM
To implement Remote Procedure Call using Java
ALGORITHM
Step 1: Start.
Step 2: Initialize the BufferedReader class to read the input.
Step 3: Create the Client and Server socket with the address and port number.
Step 4: Get the input words to open the certain application.
Step 5: Exec command to open the respective application from the client side
Step 6: Stop
PROGRAM
Client:
import java.io.*;
import java.net.*;
import java.util.*;
class Clientrpc
{
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 String");
String str=in.readLine();
dout.writeBytes(str+'\n');
clsct.close();
}
24

catch (Exception e)
{
System.out.println(e);
}
}
}
Server:
import java.io.*;
import java.net.*;
import java.util.*;
class Serverrpc
{
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();
Process p=Runtime.getRuntime().exec(str);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
OUTPUT
C:\>java Serverrpc
Client
C:\>java Clientrpc
Enter String
Calc
25

RESULT
Thus the Java program to implement Remote Procedure Call has been executed and the output was verified
successfully.
Ex.No:7
Implementation of Subnetting

AIM
To write a Java program to implement subnetting and find the subnet masks.
ALGORITHM
Step 1: Start the program.
Step 2: calculates the mask using match functions ceil() and log()
Step 3: using the AND and OR operation the addresses and its binary values are obtained.
Step 4: By using appendzero() and substring() function the continuous addresses are found
Step 5: Terminate the program
PROGRAM
import java.util.Scanner;
class Subnet
{ public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print(Enter the ip address: );
String ip = sc.nextLine();
String split_ip[] = ip.split(\\.);
String split_bip[] = new String[4];
String bip = ;
26

for(int i=0;i<4;i++){
split_bip[i] = appendZeros(Integer.toBinaryString(Integer.parseInt(split_ip[i])));
bip += split_bip[i]; }
System.out.println(IP in binary is +bip);
System.out.print(Enter the number of addresses: );
int n = sc.nextInt();
int bits = (int)Math.ceil(Math.log(n)/Math.log(2));
System.out.println(Number of bits required for address = +bits);
int mask = 32-bits;
System.out.println(The subnet mask is = +mask);
int fbip[] = new int[32];
for(int i=0; i<32;i++)
fbip[i] = (int)bip.charAt(i)-48; //convert cahracter 0,1 to integer 0,1
for(int i=31;i>31-bits;i)//Get first address by ANDing last n bits with 0
fbip[i] &= 0; String fip[] = {,,,};
for(int i=0;i<32;i++)
fip[i/8] = new String(fip[i/8]+fbip[i]);
System.out.print(First address is = );
for(int i=0;i<4;i++){
System.out.print(Integer.parseInt(fip[i],2));
if(i!=3)
System.out.print(.); }
System.out.println();
int lbip[] = new int[32];
for(int i=0; i<32;i++)
lbip[i] = (int)bip.charAt(i)-48; //convert cahracter 0,1 to integer 0,1
for(int i=31;i>31-bits;i)//Get last address by ORing last n bits with 1
lbip[i] |= 1;
String lip[] = {,,,};
for(int i=0;i<32;i++)
lip[i/8] = new String(lip[i/8]+lbip[i]);
System.out.print(Last address is = );
for(int i=0;i<4;i++){
System.out.print(Integer.parseInt(lip[i],2));
if(i!=3) System.out.print(.); }
System.out.println(); }
static String appendZeros(String s){
String temp = new String(00000000);
return temp.substring(s.length())+ s; } }
OUTPUT
Enter the ip address: 100.110.150.10
IP in binary is 01100100011011101001011000001010
Enter the number of addresses: 7
Number of bits required for address = 3
The subnet mask is = 29
First address is = 100.110.150.8
Last address is = 100.110.150.15
27

RESULT
Thus a Java program to implement subnetting and find the subnet masks has been executed and the output
was verified successfully.
Ex.No:8 Implementation TCP socket applications Echo client and echo server, Chat and File
Transfer

AIM
To implement TCP socket applications Echo client and echo server, Chat and File Transfer using Java
ECHO CLIENT AND SERVER
ALGORITHM
Step 1: start
Step 2: Include the necessary packages
Step 3: Create the socket for client and server with port number
Step 4: the message is sent from the server
Step 5: the client reads the message using the function readline() and echoes the message
Step 6: Terminate the program
PROGRAM
Client:
import java.io.*;
import java.net.*;
import java.util.*;
public class echoclient
{
public static void main(String args[])throws Exception
{
Socket c=null;
DataInputStream usr_inp=null;
DataInputStream din=new DataInputStream(System.in);
DataOutputStream dout=null;
28

try
{
c=new Socket("127.0.0.1",5678);
usr_inp=new DataInputStream(c.getInputStream());
dout=new DataOutputStream(c.getOutputStream());
}
catch(IOException e)
{
}
if(c!=null || usr_inp!=null || dout!=null)
{
String unip;
while((unip=din.readLine())!=null)
{
dout.writeBytes(""+unip);
dout.writeBytes("\n");
System.out.println("\n the echoed message");
System.out.println(usr_inp.readLine());
System.out.println("\n enter your message");
}
System.exit(0);
}
Server:
import java.io.*;
import java.net.*;
public class echoserver1
{
public static void main(String args[])throws Exception
{
ServerSocket m=null;
Socket c=null;
DataInputStream usr_inp=null;
DataInputStream din=new DataInputStream(System.in);
DataOutputStream dout=null;
try
{
m=new ServerSocket(5678);
c=m.accept();
usr_inp=new DataInputStream(c.getInputStream());
dout=new DataOutputStream(c.getOutputStream());
}
catch(IOException e)
{}
if(c!=null || usr_inp!=null)
{
String unip;
while(true)
{
System.out.println("\nMessage from Client...");
String m1=(usr_inp.readLine());
System.out.println(m1);
29

dout.writeBytes(""+m1);
dout.writeBytes("\n");
}
}
dout.close();
usr_inp.close();
c.close();
}
}
OUTPUT
Server
C:\Program Files\Java\jdk1.5.0\bin>java echoserver1
C:\Program Files\Java\jdk1.5.0\bin>
Client
C:\Program Files\Java\jdk1.5.0\bin>java echoclient
Client:
Hai Server
Server:Hai Server
Client:
Hello
Server:Hello
Client:
end
Server:end
Client:
ds
CHAT CLIENT AND CHAT SERVER
ALGORITHM
Step 1: Start
Step 2: initiate the classes Socket, DataInputStream and DataOutputStream with an object
Step 3: connect the client and server sockets through the address and the port number
Step 4: Writebytes() is used for writing the data parallel to client and the server
Step 5: readline() used fot reading the input data being communicated
Step 6: Terminate the program
PROGRAM
Client:
import java.io.*;
import java.net.*;
public class talkclient
{
public static void main(String args[])throws Exception
{
Socket c=null;
DataInputStream usr_inp=null;
DataInputStream din=new DataInputStream(System.in);
DataOutputStream dout=null;
try
{
c=new Socket("127.0.0.1",1234);
usr_inp=new DataInputStream(c.getInputStream());
dout=new DataOutputStream(c.getOutputStream());
30

}
catch(IOException e)
{}
if(c!=null || usr_inp!=null || dout!=null)
{
String unip;
System.out.println("\nEnter the message for server:");
while((unip=din.readLine())!=null)
{
dout.writeBytes(""+unip);
dout.writeBytes("\n");
System.out.println("reply");
System.out.println(usr_inp.readLine());
System.out.println("\n enter your message:");
}
System.exit(0);
}
din.close();
usr_inp.close();
c.close();
}
}
Server:
import java.io.*;
import java.net.*;
public class talkserver
{
public static void main(String args[])throws Exception
{
ServerSocket m=null;
Socket c=null;
DataInputStream usr_inp=null;
DataInputStream din=new DataInputStream(System.in);
DataOutputStream dout=null;
try
{
m=new ServerSocket(1234);
c=m.accept();
usr_inp=new DataInputStream(c.getInputStream());
dout=new DataOutputStream(c.getOutputStream());
}
catch(IOException e)
{}
if(c!=null||usr_inp!=null)
{
String unip;
while(true)
{
System.out.println("\nmessage from client:");
String m1=usr_inp.readLine();
System.out.println(m1);
31

System.out.println("enter your message:");


unip=din.readLine();
dout.writeBytes(""+unip);
dout.writeBytes("\n");
}
}
dout.close();
usr_inp.close();
c.close();
}
}
OUTPUT
C:\>java talkclient
Enter the message for server:
Hai
Reply
Hello
Enter your message:
How are you
Reply
Fine
Enter your message:
C:\>java talkserver
Message from client:
Hai
Enter your message:
Hello
Message from client:
How are you
Enter your message:
Fine
Message from client:
FILE TRANSFER CLIENT AND SERVER
ALGORITHM
Step 1: Start
Step 2: Create the client and server socket with address and port numbers
Step 3: readline() is used to read the input file data
Step 4: writebytes() is used to write the data from one file to another file
Step 5: File Reader class is used to create the file to the specific folder
Step 6: Terminate the program
PROGRAM
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));
32

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');
}
33

f.close();
dout.writeBytes("-1\n");
}}
catch(Exception e)
{ System.out.println(e);}
}
}
OUTPUT
File content
Computer networks
Transmission
Security
cryptosystems
client
Enter the file name:
sample.txt
server
Computer networks
Transmission
Security
cryptosystems
client
Enter the new file name:
net.txt
Computer networks
Transmission
Security
cryptosystems
Destination file
Computer networks
Transmission
Security
cryptosystems
34

RESULT
Thus the program for implementing TCP socket applications Echo client and echo server, Chat and File
Transfer using Java have been done successfully.
Ex.No:9
Implementation of TCP and UDP sockets applications DNS, SNMP and File Transfer

AIM
To implement TCP and UDP sockets applications DNS, SNMP and File Transfer.
DOMAIN NAME SERVICE
ALGORITHM
Step 1: Start the program
Step 2: import the package net.*
Step 3: give the host names and assigns the address virtually
Step 4: Create the datagramsocket for client and server
Step 5: Returns the host name with respect to host address assigned to them
Step 6: Terminate the program
PROGRAM
Server:
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) {
35

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

OUTPUT
$ 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
SIMPLE NETWORK MANAGEMENT PROTOCOL
ALGORITHM
Step 1: Start
Step 2: include the necessary packages for snmp
Step 3: Create object for snmpmanager with port number and address
Sep 4: Obatin the system anme and description with respect to OID value given
Step 5: Listen() method is used for listening to the users when communication takes place
Step 6: Responseevent() method is used to handle the arrival of multiple OIDs
Step 7: Target() method is used to identify that where the data should be fetched
Step 8: Obtain the answer and terminate the program
PROGRAM
import java.io.IOException;
import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.Target;
import org.snmp4j.TransportMapping;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.Address;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;
public class SNMPManager {
Snmp snmp = null;
String address = null;
public SNMPManager(String add)
{
address = add;
public static void main(String[] args) throws IOException {
SNMPManager client = new SNMPManager("udp:127.0.0.1/161");
37

client.start();
String sysDescr = client.getAsString(new OID(".1.3.6.1.2.1.1.1.0"));
System.out.println(sysDescr);
}
private void start() throws IOException {
TransportMapping transport = new DefaultUdpTransportMapping();
snmp = new
Snmp(transport);
transport.listen();
}
public String getAsString(OID oid) throws IOException {
ResponseEvent event = get(new OID[] { oid });
return event.getResponse().get(0).getVariable().toString();
}
public ResponseEvent get(OID oids[]) throws IOException {
PDU pdu = new PDU();
for (OID oid : oids) {
pdu.add(new VariableBinding(oid));
}
pdu.setType(PDU.GET);
ResponseEvent event = snmp.send(pdu, getTarget(), null);
if(event != null) {
return event;
}
throw new RuntimeException("GET timed out");
}
private Target getTarget() {
Address targetAddress = GenericAddress.parse(address);
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString("public"));
target.setAddress(targetAddress);
target.setRetries(2);
target.setTimeout(1500);
target.setVersion(SnmpConstants.version2c);
return target;
}}
OUTPUT
Hardware: x86 Family 6 Model 23 Stepping 10 AT/AT COMPATIBLE Software:
Windows 2007 Version 5.1 (Build 2600 Multiprocessor Free)
FILE TRANSFER
ALGORITHM
Step 1: Start
Step 2: Create the client and server socket with address and port numbers
Step 3: readline() is used to read the input file data
Step 4: writebytes() is used to write the data from one file to another file
Step 5: File Reader class is used to create the file to the specific folder
Step 6: Terminate the program
PROGRAM
Client:
Import java.io.*;
38

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);
39

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
client
Enter the file name: sample.txt
server
Computer networks
client
Enter the new file name: net.txt
Computer networks
Destination file
Computer networks
40

RESULT
Thus the Java program is done to create TCP and UDP sockets applications DNS, SNMP and File Transfer
and verified successfully
Ex.No:10 Study of Network Simulator and simulation of congestion Control Algorithms using
NS

AIM
To Study of Network simulator (NS).and Simulation of Congestion Control
Algorithms using network simulator.
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 overview
Ns Status
Periodical release (ns-2.26, Feb 2003)
Platform support
FreeBSD, Linux, Solaris, Windows and Mac
Ns functionalities
Routing, Transportation, Traffic sources,Queuing disciplines, QoS
Wireless
Ad hoc routing, mobile IP, sensor-MAC Tracing, visualization and various utilities NS(Network
Simulators)
Most of the commercial simulators are GUI driven, while some network simulators are CLI driven. The
network model / configuration describes the state of the network (nodes,routers, switches, links) and the
events (data transmissions, packet error etc.). An important output of simulations are the trace files. Trace
files log every packet, every event that occurred in the simulation and are used for analysis. Network
simulators can also provide other tools to facilitate visual analysis of trends and potential trouble spots.
Most network simulators use discrete event simulation, in which a list of pending "events" is stored, and
those events are processed in order, with some events triggering future events such as the event of the
arrival of a packet at one node triggering the event of the arrival of that packet at a downstream node.
Simulation of networks is a very complex task. For example, if congestion is high, then estimation of the
average occupancy is challenging because of high variance. To estimate the likelihood of a buffer
overflow in a network, the time required for an accurate answer can be extremely large. Specialized
techniques such as "control variates" and "importance sampling" have been developed to speed
simulation.
41

Examples of network simulators


There are many both free/open-source and proprietary network simulators. Examples of notable network
simulation software are, ordered after how often they are mentioned in research papers:
1. ns (open source)
2. OPNET (proprietary software)
3. 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, analyze various
standard results apart from devising some novel protocol or strategy for routing etc. Network simulators
are also widely used to simulate battlefield networks in Network-centric warfare
There are a wide variety of network simulators, ranging from the very simple to the very complex.
Minimally, a network simulator must enable a user to represent a network topology, specifying the nodes
on the network, the links between those nodes and the traffic between the nodes. More complicated
systems may allow the user to specify everything about the protocols used to handle traffic in a network.
Graphical applications allow users to easily visualize the workings of their simulated environment. Text-
based applications may provide a less intuitive interface, but may permit more advanced forms of
customization.
Packet loss
Occurs when one or more packets of data travelling across a computer network fail to reach their
destination. Packet loss is distinguished as one of the three main error types encountered in digital
communications; the other two being bit errorand spurious packets caused due to noise. Packets can be
lost in a network because they may be dropped when a queue in the network node overflows. The amount
of packet loss during the steady state is another important property of a congestion control scheme. The
larger the value of packet loss, the more difficult it is for transport layer protocols to maintain high
bandwidths, the sensitivity to loss of individual packets, as well as to frequency and patterns of loss
among longer packet sequences is strongly dependent on the application itself.
Throughput
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 successful
message delivery over a communication channel. The throughput is usually measured in bits per second
(bit/s or bps), and sometimes in data packets 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
42

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.
NS2 Execution
The overall simulation procedure in NS is shown below. NS is composed of OTcl Script and Interpreter. NS
simulation results can be observed through graphs by analyzing the trace file or viewing animations with
NAM.
$ ns filename.tcl
NS2 Program Elements
Event Scheduler
a Creating event scheduler
set ns [new Simulator]
b Schedule events
$ns at time " event"
c Start scheduler
$ns run
Creating Network
a Create set of Nodes
set n0 [$ns node]
set n1 [$ns node]
b Create links and queuing
$ns duplex-link $n0 $n1 bandwidth delay queue_type
Bandwidth is generally in MB
Delay is generally in ms
Queue type is either DropTail, RED, CBQ, FQ, SFQ, etc
$ns duplex-link $n0 $n2 1Mb 10ms DropTail
c Layout
$ns duplex-link-op $n0 $n2 orient position
where position is either right, right-up, right-down, left, leftup, left-down, up, down
d Marking flows
$ns color 1 Blue
$ns color 2 Red
$udp0 set class_ 1
$udp1 set class_ 2
Tracing
a NAM Trace all links (must succeed scheduler creation)
set nf [open out.nam w]
$ns namtrace-all $nf
b Trace all links (must succeed scheduler creation)
set tf [open out.tr w]
$ns trace-all $tf
43

Trace file ouput format


event, time, from_node, to_node, pkt type, pkt size, flags, fid, src_addr, dst_addr,
seq_num, pkt_id
where events are r received, + enqueued, - dequeued, d dropped
c Tracing specific links
$ns trace-queue $n0 $n1
$ns namtrace-queue $n0 $n1
Connection
a UDP
set udp [new Agent/UDP]
set null [new Agent/Null]
$ns attach-agent $n0 $udp0
$ns attach-agent $n1 $null
$ns connect $udp0 $null
b TCP
set tcp0 [new Agent/TCP/FullTcp]
$tcp0 set window_ 30
$tcp0 set segsize_ 536
$ns attach-agent $n0 $tcp0
set sink0 [new Agent/TCP/FullTcp]
$ns attach-agent $n5 $sink0
$sink0 listen
$ns connect $tcp0 $sink0
Traffic Generation
a UDP
set src [new Application/Traffic/type]
$src attach-agent $udp0
where type is either CBR, Exponential, Pareto
b TCP
set ftp [new Application/FTP]
$ftp attach-agent $tcp
set telnet [new Application/Telnet]
$telnet attach-agent $tcp
Finish procedure
a Flush NS tracing, Close tracing files and execute any post-analysis programs
(display results, run NAM, etc)
proc finish {} {
global ns nf
$ns flush-trace
close $nf
exec nam out.nam &
exit 0
}
SIMULATION OF CONGESTION CONTROL
ALGORITHM
Step 1: Create a simulator object
Step 2: Define different flows for data flows
Step 3: Trace all events in a nam file and text file
Step 4: Create source nodes (s1, s2, s3), gateway (G) and receiver (r)
Step 5: Describe their layout topology
Step 6: Specify the link between nodes
44

Step 7: Define the queue size between nodes G and r as 5


Step 8: Monitor queue on all links vertically 90
Step 9: Create TCP agents tcp1, tcp2, tcp3 and attach it to nodes s1, s2and s3respectively
Step10: Create three TCP sinks and attach it to node r
Step 11: Connect traffic sources to the sink
Step 12: Create FTP agents ftp1, ftp2, ftp3and attach it to tcp1, tcp2and tcp3respectively
Step 13: Label the nodes at start time
Step 14: Schedule ftp1, ftp2, ftp3to start at 0.1 and stop at 5.0 seconds
Step 15: Call finish procedure at 5.25 seconds
Step 16: Run the simulation
Step 17: Execute NAM on the trace file
Step 18: Observe the simulated events on the NAM editor and packet flow on link G to r
Step 19: View the trace file and analyze the events
Step 20: Stop
PROGRAM
TCP.tcl
#Create a simulator object
set ns [new Simulator]
#Open trace files
set f [open droptail-queue-out.tr w]
$ns trace-all $f
#Open the nam trace file
set nf [open droptail-queue-out.nam w]
$ns namtrace-all $nf
#s1, s2 and s3 act as sources.
set s1 [$ns node]
set s2 [$ns node]
set s3 [$ns node]
#G acts as a gateway
set G [$ns node]
#r acts as a receiver
set r [$ns node]
#Define different colors for data flows
$ns color 1 red
$ns color 2 SeaGreen
$ns color 3 blue
#Create links between the nodes
$ns duplex-link $s1 $G 6Mb 10ms DropTail
$ns duplex-link $s2 $G 6Mb 10ms DropTail
$ns duplex-link $s3 $G 6Mb 10ms DropTail
$ns duplex-link $G $r 3Mb 10ms DropTail
#Define the layout of the nodes
$ns duplex-link-op $s1 $G orient right-up
$ns duplex-link-op $s2 $G orient right
$ns duplex-link-op $s3 $G orient right-down
$ns duplex-link-op $G $r orient right
#Define the queue size for the link between node G and r
$ns queue-limit $G $r 5
#Monitor the queues for links vertically
$ns duplex-link-op $s1 $G queuePos 0.5
$ns duplex-link-op $s2 $G queuePos 0.5
45

$ns duplex-link-op $s3 $G queuePos 0.5


$ns duplex-link-op $G $r queuePos 0.5
#Create a TCP agent and attach it to node s1
set tcp1 [new Agent/TCP/Reno]
$ns attach-agent $s1 $tcp1
$tcp1 set window_ 8
$tcp1 set fid_ 1
#Create a TCP agent and attach it to node s2
set tcp2 [new Agent/TCP/Reno]
$ns attach-agent $s2 $tcp2
$tcp2 set window_ 8
$tcp2 set fid_ 2
#Create a TCP agent and attach it to node s3
set tcp3 [new Agent/TCP/Reno]
$ns attach-agent $s3 $tcp3
$tcp3 set window_ 4
$tcp3 set fid_ 3
#Create TCP sink agents and attach them to node r
set sink1 [new Agent/TCPSink]
set sink2 [new Agent/TCPSink]
set sink3 [new Agent/TCPSink]
$ns attach-agent $r $sink1
$ns attach-agent $r $sink2
$ns attach-agent $r $sink3
#Connect the traffic sources with the traffic sinks
$ns connect $tcp1 $sink1
$ns connect $tcp2 $sink2
$ns connect $tcp3 $sink3
#Create FTP applications and attach them to agents
set ftp1 [new Application/FTP]
$ftp1 attach-agent $tcp1
set ftp2 [new Application/FTP]
$ftp2 attach-agent $tcp2
set ftp3 [new Application/FTP]
$ftp3 attach-agent $tcp3
#Define a 'finish' procedure
proc finish {} {
global ns
$ns flush-trace
puts "running nam..."
exec nam -a droptail-queue-out.nam &
exit 0
}
#Define label for nodes
$ns at 0.0 "$s1 label Sender1"
$ns at 0.0 "$s2 label Sender2"
$ns at 0.0 "$s3 label Sender3"
$ns at 0.0 "$G label Gateway"
$ns at 0.0 "$r label Receiver"
#Schedule ftp events
$ns at 0.1 "$ftp1 start"
46

$ns at 0.1 "$ftp2 start"


$ns at 0.1 "$ftp3 start"
$ns at 5.0 "$ftp1 stop"
$ns at 5.0 "$ftp2 stop"
$ns at 5.0 "$ftp3 stop"
#Call finish procedure after 5 seconds of simulation time
$ns at 5.25 "finish"
#Run the simulation
$ns run
OUTPUT
$ ns TCP.tcl
47

RESULT
Thus the study of network simulator and simulation of TCP congestion control algorithm is done and verified
successfully.
Ex.No:11 Case study of Routing Algorithms Link State Routing, Flooding and Distant Vector
Routing

AIM
To make a case study of of Routing Algorithms Link State Routing, Flooding and Distant Vector Routing and
implement using NS2 Network Simulator .
LINK STATE ROUTING
ALGORITHM
Step 1: Create a simulator object
Step 2: Set routing protocol to Link State routing
Step 3: Trace packets on all links onto NAM trace and text trace file
Step 4: Define finish procedure to close files, flush tracing and run NAM
Step 5: Create eight nodes
Step 6: Specify the link characteristics between nodes
Step 7: Describe their layout topology as a octagon
Step 8: Add UDP agent for node n1
Step 9: Create CBR traffic on top of UDP and set traffic parameters.
Step 10: Add a sink agent to node n4
Step 11: Connect source and the sink
Step 12: Schedule events as follows:
a. Start traffic flow at 0.5
b. Down the link n3-n4 at 1.0
c. Up the link n3-n4 at 2.0
d. Stop traffic at 3.0
e. Call finish procedure at 5.0
Step 13: Start the scheduler
Step 14: Observe the traffic route when link is up and down
Step 15: View the simulated events and trace file analyze it
Step 16: Stop
PROGRAM
#Link State routing protocol ls.tcl
#Create a simulator object
set ns [new Simulator]
#Use Link State routing
$ns rtproto LS
#Open the nam trace file
set nf [open out.nam w]
$ns namtrace-all $nf
# Open tracefile
set nt [open trace.tr w]
$ns trace-all $nt
#Define 'finish' procedure
proc finish {} {
global ns nf
$ns flush-trace
#Close the trace file
48

close $nf
#Execute nam on the trace file
exec nam -a out.nam &
exit 0
}
# Create 8 nodes
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
set n6 [$ns node]
set n7 [$ns node]
set n8 [$ns node]
# Specify link characterestics
$ns duplex-link $n1 $n2 1Mb 10ms DropTail
$ns duplex-link $n2 $n3 1Mb 10ms DropTail
$ns duplex-link $n3 $n4 1Mb 10ms DropTail
$ns duplex-link $n4 $n5 1Mb 10ms DropTail
$ns duplex-link $n5 $n6 1Mb 10ms DropTail
$ns duplex-link $n6 $n7 1Mb 10ms DropTail
$ns duplex-link $n7 $n8 1Mb 10ms DropTail
$ns duplex-link $n8 $n1 1Mb 10ms DropTail
# Specify layout as a octagon
$ns duplex-link-op $n1 $n2 orient left-up
$ns duplex-link-op $n2 $n3 orient up
$ns duplex-link-op $n3 $n4 orient right-up
$ns duplex-link-op $n4 $n5 orient right
$ns duplex-link-op $n5 $n6 orient right-down
$ns duplex-link-op $n6 $n7 orient down
$ns duplex-link-op $n7 $n8 orient left-down
$ns duplex-link-op $n8 $n1 orient left
#Create a UDP agent and attach it to node n1
set udp0 [new Agent/UDP]
$ns attach-agent $n1 $udp0
#Create a CBR traffic source and attach it to udp0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0
#Create a Null agent (a traffic sink) and attach it to node n4
set null0 [new Agent/Null]
$ns attach-agent $n4 $null0
#Connect the traffic source with the traffic sink
$ns connect $udp0 $null0
#Schedule events for the CBR agent and the network dynamics
49

$ns at 0.0 "$n1 label Source"


$ns at 0.0 "$n4 label Destination"
$ns at 0.5 "$cbr0 start"
$ns rtmodel-at 1.0 down $n3 $n4
$ns rtmodel-at 2.0 up $n3 $n4
$ns at 4.5 "$cbr0 stop"
#Call the finish procedure after 5 seconds of simulation time
$ns at 5.0 "finish"
#Run the simulation
$ns run
OUTPUT
$ ns ls.tcl
50

FLOODING
ALGORITHM
Step 1: Create a simulator object
Step 2: Set the options for flooding
Step 3: Trace packets on all links onto NAM trace and text trace file
Step 4: Define finish procedure to close files, flush tracing and run NAM
Step 5: Create nodes
Step 6: Specify the link characteristics between nodes
Step 7: Describe their layout topology
Step 8: Add UDP agent
Step 9: Create CBR traffic on top of UDP and set traffic parameters.
Step 10: Add a sink agent to node
Step 11: Connect source and the sink
Step 12: Schedule events.
Step 13: Start the scheduler
Step 14: Observe the traffic route when link is up and down
Step 15: View the simulated events and trace file analyze it
Step 16: Stop
PROGRAM
#Flooding routing protocol flood.tcl
# Define options
set val(chan) Channel/WirelessChannel
set val(prop) Propagation/FreeSpace
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(x) 670
set val(y) 670
set val(ifqlen) 50
set val(seed) 0.0
set val(adhocRouting) FLOODING
set val(nn) 2
set val(stop) 200.0
# create simulator instance
set ns_ [new Simulator]
# setup topography object
set topo [new Topography]
#use new trace format
$ns_ use-newtrace
# create trace object for ns and nam
set tracefd [open flood.tr w]
$ns_ trace-all $tracefd
set namtrace [open flood.nam w]
$ns_ namtrace-all-wireless $namtrace $val(x) $val(y)

# define topology
51

$topo load_flatgrid $val(x) $val(y)


# Create God
set god_ [create-god $val(nn)]
# Create channel #1
set chan_1_ [new $val(chan)]
#global node setting
$ns_ node-config -adhocRouting $val(adhocRouting) \
-llType $val(ll) \
-macType $val(mac) \
-ifqType $val(ifq) \
-ifqLen $val(ifqlen) \
-antType $val(ant) \
-propType $val(prop) \
-phyType $val(netif) \
-topoInstance $topo \
-agentTrace ON \
-routerTrace ON \
-macTrace OFF \
-mobilityTrace OFF \
-channel $chan_1_
# Create the specified number of nodes [$val(nn)] and "attach" them to the channel.
for {set i 0} {$i < $val(nn) } {incr i} {
set node_($i) [$ns_ node $i]
$node_($i) random-motion 0
}
$god_ set-dist 0 1 1
#setting initial positions of the nodes
#nodes are stationary for throughout the simulation
$node_(0) set Z_ 0.000000000000
$node_(0) set Y_ 0.00
$node_(0) set X_ 0.00
$node_(1) set Z_ 0.000000000000
$node_(1) set Y_ 0.0
$node_(1) set X_ 10.0
#creating a CBR flow from node 0 to node 1
set udp_(0) [new Agent/UDP]
$ns_ attach-agent $node_(0) $udp_(0)
set null_(0) [new Agent/Null]
$ns_ attach-agent $node_(1) $null_(0)
set cbr_(0) [new Application/Traffic/CBR]
$cbr_(0) set packetSize_ 512
$cbr_(0) set interval_ .0025
$cbr_(0) set random_ false
$cbr_(0) set maxpkts_ 1
$cbr_(0) attach-agent $udp_(0)
$ns_ connect $udp_(0) $null_(0)
52

$ns_ at 5.00 "$cbr_(0) start"


# Tell nodes when the simulation ends
for {set i 0} {$i < $val(nn) } {incr i} {
$ns_ at $val(stop).0 "$node_($i) reset";
}
$ns_ at $val(stop).0002 "puts \"NS EXITING...\" ; $ns_ halt"
puts "Starting Simulation..."
$ns_ run
Execution:$ ns flood.tcl
DISTANT VECTOR ROUTING
ALGORITHM
Step 1: Create a simulator object
Step 2: Set routing protocol to Distance Vector routing
Step 3: Trace packets on all links onto NAM trace and text trace file
Step 4: Define finish procedure to close files, flush tracing and run NAM
Step 5: Create eight nodes
Step 6: Specify the link characteristics between nodes
Step 7: Describe their layout topology as a octagon
Step 8: Add UDP agent for node n1
Sep 9: Create CBR traffic on top of UDP and set traffic parameters.
Step 10: Add a sink agent to node n4
Step 11: Connect source and the sink
Step 12: Schedule events as follows:
a. Start traffic flow at 0.5
b. Down the link n3-n4 at 1.0
c. Up the link n3-n4 at 2.0
d. Stop traffic at 3.0
e. Call finish procedure at 5.0
Step 13: Start the scheduler
Step 14: Observe the traffic route when link is up and down
Step 15: View the simulated events and trace file analyze it
Step 16: Stop
PROGRAM
#Distance vector routing protocol distvect.tcl
#Create a simulator object
set ns [new Simulator]
#Use distance vector routing
$ns rtproto DV
#Open the nam trace file
set nf [open out.nam w]
$ns namtrace-all $nf
# Open tracefile
set nt [open trace.tr w]
$ns trace-all $nt
#Define 'finish' procedure
proc finish {} {
global ns nf
$ns flush-trace
#Close the trace file
close $nf
53

#Execute nam on the trace file


exec nam -a out.nam &
exit 0
}
# Create 8 nodes
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
set n6 [$ns node]
set n7 [$ns node]
set n8 [$ns node]
# Specify link characterestics
$ns duplex-link $n1 $n2 1Mb 10ms DropTail
$ns duplex-link $n2 $n3 1Mb 10ms DropTail
$ns duplex-link $n3 $n4 1Mb 10ms DropTail
$ns duplex-link $n4 $n5 1Mb 10ms DropTail
$ns duplex-link $n5 $n6 1Mb 10ms DropTail
$ns duplex-link $n6 $n7 1Mb 10ms DropTail
$ns duplex-link $n7 $n8 1Mb 10ms DropTail
$ns duplex-link $n8 $n1 1Mb 10ms DropTail
# specify layout as a octagon
$ns duplex-link-op $n1 $n2 orient left-up
$ns duplex-link-op $n2 $n3 orient up
$ns duplex-link-op $n3 $n4 orient right-up
$ns duplex-link-op $n4 $n5 orient right
$ns duplex-link-op $n5 $n6 orient right-down
$ns duplex-link-op $n6 $n7 orient down
$ns duplex-link-op $n7 $n8 orient left-down
$ns duplex-link-op $n8 $n1 orient left
#Create a UDP agent and attach it to node n1
set udp0 [new Agent/UDP]
$ns attach-agent $n1 $udp0
#Create a CBR traffic source and attach it to udp0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0
#Create a Null agent (a traffic sink) and attach it to node n4
set null0 [new Agent/Null]
$ns attach-agent $n4 $null0
#Connect the traffic source with the traffic sink
$ns connect $udp0 $null0
#Schedule events for the CBR agent and the network dynamics
$ns at 0.0 "$n1 label Source"
$ns at 0.0 "$n4 label Destination"
$ns at 0.5 "$cbr0 start"
$ns rtmodel-at 1.0 down $n3 $n4
$ns rtmodel-at 2.0 up $n3 $n4
$ns at 4.5 "$cbr0 stop"
54

#Call the finish procedure after 5 seconds of simulation time


$ns at 5.0 "finish"
#Run the simulation
$ns run
OUTPUT
$ ns distvect.tcl
55

RESULT
Thus the experiment is done to make a case study of Routing Algorithms Link State Routing, Flooding and
Distant Vector Routing and implement using NS2 Network Simulator.
Ex.No:12 Implementation of CSMA/CD in NS2
56

AIM
To implement CSMA/CD using Network Simulator 2.
ALGORITHM
Step 1: Create a simulator object
Step 2: Set different color for TCP and UDP traffic.
Step 3: Trace packets on all links onto NAM trace and text trace file
Step 4: Define finish procedure to close files, flush tracing and run NAM
Step 5: Create six nodes
Step 6: Specify the link characteristics between nodes
Step 7: Create a LAN with nodes n3, n4, n5 part of it
Step 8: Describe layout topology of nodes
Step 9: Add UDP agent for node n1
Step 10: Create CBR traffic on top of UDP and set traffic parameters.
Step 11: Add a null agent to node and connect it to udp source
Step 12: Add TCP agent for node n0
Step 13: Create FTP traffic for TCP and set its parameters
Step 14: Add a sink to TCP and connect it to source
Step 15: Schedule events as follows:
a. Start CBR & FTP traffic flow at 0.3 and 0.8 respectively
b. Stop CBR & FTP traffic flow at 7.5 and 7.0 respectively
c. Call finish procedure at 8.0
Step 16: Start the scheduler
Step 17: Observe the transmission of packets over LAN
Step 18: View the simulated events and trace file analyze it
Step 19: Stop
PROGRAM
#Lan simulation mac.tcl
set ns [new Simulator]
#define color for data flows
$ns color 1 Purple
$ns color 2 MAgenta
#open tracefile
set tracefile1 [open out.tr w]
$ns trace-all $tracefile1
#open nam file
set namfile [open out.nam w]
$ns namtrace-all $namfile
#define the finish procedure
proc finish {} {
global ns tracefile1 namfile
$ns flush-trace
close $tracefile1
close $namfile
exec nam out.nam &
exit 0
}
#create six nodes
set n0 [$ns node]
set n1 [$ns node]
57

set n2 [$ns node]


set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
# Specify color and shape for nodes
$n1 color MAgenta
$n1 shape box
$n5 color MAgenta
$n5 shape box
$n0 color Purple
$n4 color Purple
#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
# Create a LAN
set lan [$ns newLan "$n3 $n4 $n5" 0.5Mb 40ms LL Queue/DropTail
MAC/Csma/Cd Channel]
#Give node position
$ns duplex-link-op $n0 $n2 orient right-down
$ns duplex-link-op $n1 $n2 orient right-up
$ns simplex-link-op $n2 $n3 orient right
$ns simplex-link-op $n3 $n2 orient left
#setup 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 packet_size_ 552
#set ftp over tcp connection
set ftp [new Application/FTP]
$ftp attach-agent $tcp
#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.05Mb
$cbr set random_ false
#scheduling the events
$ns at 0.0 "$n0 label TCP_Traffic"
58

$ns at 0.0 "$n1 label UDP_Traffic"


$ns at 0.3 "$cbr start"
$ns at 0.8 "$ftp start"
$ns at 7.0 "$ftp stop"
$ns at 7.5 "$cbr stop"
$ns at 8.0 "finish"
$ns run
OUTPUT
$ ns mac.tcl

RESULT
Thus the CSMA/CD using Network Simulator has been implemented successfully.

Вам также может понравиться