CN-LAB Manual (Proper)
CN-LAB Manual (Proper)
Manual
COMPUTER NETWORKS
LAB MANUAL
III YEAR
VI SEMESTER
ACADEMIC YEAR: 2023-2024
List of Experiments
Sl. Experiment
No
1 Study of Socket Programming
2 Finding The IP Address
TCP Sockets
3 TCP-One Way Communication
4 TCP-Two Way Communication
5 Date Time Server
6 Echo Command
7 File Transfer
UDP Communication
8 UDP-One Way Communication
9 UDP-Two Way Communication
10 UDP DNS Server/Client
Raw Socket Programming
11 Ping Command
12 Talk Command
Remote Invocations
Remote Method Invocation-
13
Factorial of a given number
14 Simple Calculator
15 Remote Command Execution
Using Simulators
16 Study of NS2
17 Simple Topology Creation using NS - 2
18 Performance comparison of MAC protocols
19 Distance Vector routing using NS2
20 Study of TCP/UDP performance.
Content Beyond the Syllabus
21 Implementation of Subnetting
22 socket for HTTP for web page upload and download
23 Implementing A Wireless Sensor Network
24 Simulate A Mobile Adhoc Network
AIM
To study the various methods of Socket programming.
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 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.
After the connections are established, communication can occur using I/O
streams. Each socket has both an OutputStream and an InputStream. The
TCP/IP PROTOCOL
TCP/IP Sockets are used to implement, reliable, bidirectional, persistent,
point to point stream-based connection between host on the internet. TCP/IP
provides end-to-end connectivity specifying how data should be formatted,
addressed, transmitted, routed and received at the destination.
There are two types of sockets available:1. ServerSocket and 2. Socket.
They connect to them on published ports when the ServerSocket created it will
register itself with the system as having an internet in client connection. A
server socket waits for requests to come in over the network. It performs some
operation based on that request, and then possibly returns a result to the
requester.
SERVERSOCKET CLASS:
The java.net.ServerSocket class is used by server applications to obtain a
port and listen for client requests
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.
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.
CLIENT SOCKET
The creation of socket is done through the constructor of the class
socket. The creation of the socket objects implicates establishes a connection
between the client and the server. he 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.
CONSTRUCTOR OF SERVERSOCKET
Methods Description
CONSTRUCTOR OF SOCKET
Methods Description
This method attempts to connect to
the specified server at the specified
public Socket(String host, int port) port. If this constructor does not
throws UnknownHostException throw an exception, the connection is
successful and the client is
connected to the server.
public Socket(InetAddress host, int This method is identical to the
port) throws IOException previous constructor, except that the
METHODS
The following I/O Streams related methods are also available in the socket.
Methods Description
InputStream getInput Stream() Return the InputStream associated
with the invoking socket.
OutputStream get outputstream() Return the output stream associated
with the invoking socket.
Void close Close both the inputstream and
outputstream.
INET ADDRESSING
Every computer on the internet has an address. An internet is a number
that uniquely identifies each computer on the net. There are 32bit in an IP
Address and we often refer to them has sequence of four number between 0
and 255 separated by the data. This makes them easier to remember because
they are not randomly assigned, they are hierarchically assigned. The first few
bits define which class of network lettered A, B, C, D or E. The address
represents internet or on a class C network since there are 2 million networks in
class C.
Methods Description
static InetAddress
Returns an InetAddress object
getByAddress(byte[] addr)
given the raw IP address .
VIVA QUESTIONS
1. What is a Socket?
Sockets are the fundamental technology for programming software to
communicate on TCP/IP networks. A socket provides a bidirectional
communication endpoint for sending and receiving data with another socket.
AIM
To write a java program to find the IP address of the system.
ALGORITHM
Step 1: Start the program
Step 2: Create an object for the class InetAddress.
Step 3: The IP address of the system is retrieved using the method
getLocalHost().
Step 4: The system name is retrieved using the method getHostName().
Step 5: The IP address of other system can be retrieved using the
method getByName(),by passing the system name as
parameter.
Step 6: Stop the program.
SOURCE CODE
import java.io.*;
import java.net.*;
class address
{
public static void main (String args [])throws UnknownHostException
{
// To get local machine’s IP address
InetAddress ip=InetAddress.getLocalHost();
// Gets the local machine’s name
System.out.println("\n IP address is :"+ip);
String s1= ip.getHostName();
System.out.println("\n System name is:"+s1);
//To receive other machine’s name
ip=InetAddress.getByName("MITIT080");
System.out.println("\n Name of other system is :"+ip);
}
}
OUTPUT
RESULT
Thus the java program to find the IP address is executed and output is
verified successfully.
VIVA QUESTIONS
1. What is an IP address?
An Internet Protocol address (IP address) is a numerical label
assigned to each device (e.g., computer, printer) participating in a computer
network that uses the Internet Protocol for communication.
AIM
To write a java program to implement one way communication using TCP
ALGORITHM
SERVER
Step 1: Start the program.
Step 2: Import the necessary java.net package and other packages.
Step 3: Create objects for ServerSocket, Socket, DataInputStream and
PrintStream to transfer
the data.
Step 4: The readLine method reads the message .
Step 5: Using PrintStream transfer the data in OutputStream via a port.
Step 6: The data is transferred from server until an “end ” string occurs.
Step 7: If an “end ” is encountered, close the socket and exit the
program.
Step 8: Stop the program.
CLIENT
Step 1: Start the program.
Step 2: Import the necessary java.net package and other packages.
Step 3: Create objects for Socket and DataInputStream to receive the
server data.
Step 4: The getInputStream method gets the data from the socket.
Step 5: The readLine method reads the message received from server.
Step 6: The socket will close, when an end is encountered
Step 8: Stop the program.
SOURCE CODE
CLIENT
import java.io.*;
import java.net.*;
class TcpOneWayChatClient
{
CLIENT
RESULT
Thus the TCP one way communication program is executed and output is
verified successfully.
VIVA QUESTIONS
1. Expand TCP.
Transmission Control Protocol
2. What is TCP one way communication mean?
It is the process of transmitting data either from a server or a client in one
direction. i.e only the sender will transmit data.
3. In which layer does TCP exist?
In the transport layer
4. What form of communication does TCP represent?
Stream communication
5. What is the purpose of a readline method?
The readline method reads the user input
AIM
To write a java program to implement two way communication using TCP
ALGORITHM
SERVER
Step 1: Start the Program.
Step 2: Import java.net package and other packages.
Step 3: Create objects for ServerSocket, Socket and PrintStream to
transfer message from server.
Step 4: Create object for DataInputStream to receive the client data.
Step 5: The readLine method reads the message entered by the server
Step 6: The PrintStream class transfers the data through the
OutputStream via a port.
Step 7: Using if statement , message is transmitted until an “end” string is
transferred.
Step 8: Using another if statement, message is received until an “end”
string is found
Step 9: Close the socket and Stop the program.
CLIENT
Step 1: Start the Program.
Step 2: Import java.net package and other packages.
Step 3: Create object for Socket to connect to the specified port.
Step 4: Create object for DataInputStream and PrintStream to send and
receive message.
Step 5: The readLine method reads the message received from the server
Step 6: Using if statement, message is received until an “end” string is
found
Step 7: Using another if statement , message is transmitted until an “end”
string is entered
Step 8: Close the socket and Stop the program
SOURCE CODE
CLIENT
import java.io.*;
import java.net.*;
import java.lang.*;
class TcpTwoWayChatClient
{
public static void main(String args[])throws IOException
{
String str, str1;
// Creates object for socket
//Establishes connection to the specified IP and Port Number
Socket sock=new Socket("LocalHost",8000);
//Receives the data from the socket
DataInputStream mydis=new DataInputStream(sock.getInputStream());
//Reads the message from the keyboard
Scanner s=new Scanner (System.in);
//Transmits data to the socket
PrintStream ps =new PrintStream(sock.getOutputStream());
System.out.println("Connection established successfully!");
System.out.println("You can start chat now!");
System.out.println("Enter 'end' to quit from chat");
System.out.println("Listening for server...");
while(true)
{
//Reads the message received from the server
str=mydis.readLine();
System.out.println("Msg received at Server::"+str);
//Checks for end of message
if(str.equals("end"))
{
//Closes the socket
sock.close();
break;
}
System.out.println("Enter the msg to send: ");
//Reads the message to be sent
str1=s.nextLine();
ps.println(str1);
//Checks for end of message
if(str1.equals("end"))
{
//Closes the socket
sock.close();
break;
}
}
}
}
SERVER
import java.io.*;
import java.net.*;
import java.lang.*;
import java.util.*;
class TcpTwoWayChatServer
{
public static void main(String a[])throws IOException
{
String str, str1;
//Creates the server socket for the specified port
ServerSocket servsock=new ServerSocket(8000);
//Opens the socket and binds the connection
Socket sock=servsock.accept();
//Transmits data to the socket
PrintStream ps=new PrintStream(sock.getOutputStream());
//To read the data
Scanner s=new Scanner(System.in);
//Receives the data from the socket
DataInputStream mydis=new DataInputStream(sock.getInputStream());
System.out.println("Connection established successfully!");
System.out.println("You can start chat now!");
System.out.println("Enter 'end' to quit from chat");
while(true)
{
System.out.println("Server:");
CLIENT
RESULT
Thus the java program for TCP two way communication is executed and
output is verified successfully
VIVA QUESTIONS
AIM:-
To write a java program to implement Date and Time Server using TCP.
import java.io.*;
import java.net.*;
class DateClient
{
public static void main(String args[]) throws Exception
{
Socket soc=new Socket(InetAddress.getLocalHost(),5217);
BufferedReader in=new BufferedReader( new InputStreamReader(
soc.getInputStream() ) );
System.out.println(in.readLine());
}
}
// Date Server
import java.net.*;
import java.io.*;
import java.util.*;
class DateServer
{
public static void main(String args[]) throws Exception
{
ServerSocket s=new ServerSocket(5217);
while(true)
{
System.out.println("Waiting For Connection ...");
Socket soc=s.accept();
DataOutputStream out=new
DataOutputStream(soc.getOutputStream());
out.writeBytes("Server Date" + (new Date()).toString() + "\n");
out.close();
soc.close();
}
}
}
OUTPUT:-
RESULT:-
Thus Date and Time sever program using TCP is executed and output is
verified.
AIM
To write a program in java to demonstrate the ECHO command.
ALGORITHM
ECHO SERVER
1. Start the program.
2. Import java.net and other necessary packages.
3. In a try block, create objects for Socket, ServerSocket, BufferedReader
and PrintStream
4. GetInputstream and GetOutputstream methods are used to receive
and send message.
5. Store the message in a string and display the message
6. Send the same received message to the client using println.
ECHO CLIENT
1. Start the program.
2. Import java.net and other necessary packages.
3. Create an object for Inetaddress to get localhost IP address.
4. Create object for the socket class and establish connection in the port
number 9000.
5. Create objects for Printstream and bufferedreader.
6. GetInputstream and getoutputstream methods are used to receive and
send message.
7. Get the user input and store it in a string.
8. Pass the message to the server through the socket using println
method.
9. The readline method reads the echo message from the server.
10. The received message is displayed.
SOURCE CODE
ECHO SERVER
import java.net.*;
import java.io.*;
public class EchoServer
{
public static void main(String args[])
{
String line;
try
{
ServerSocket sersoc = new ServerSocket(9000);
Socket soc = sersoc.accept();
BufferedReader br = new BufferedReader(new
InputStreamReader(soc.getInputStream()));
PrintStream ps = new PrintStream(soc.getOutputStream());
while(true)
{
line = br.readLine();
System.out.println("Received from Client: " + line);
ps.println(line);
}
}
catch(IOException e)
{
System.out.println(e);
}
}
}
ECHO CLIENT
import java.net.*;
import java.io.*;
import java.util.*;
public class EchoClient
{
public static void main(String arg[])
{
String line;
try
{
InetAddress ip = InetAddress.getLocalHost();
Socket soc = new Socket(ip,9000);
PrintStream ps = new PrintStream(soc.getOutputStream());
Scanner s=new Scanner(System.in);
BufferedReader br = new BufferedReader(new
InputStreamReader(soc.getInputStream()));
while(true)
{
System.out.print("Client: ");
line = s.nextLine();
ps.println(line);
System.out.println("Echo from Server: " + br.readLine());
}
}
catch(IOException e)
{
System.out.println(e);
}
}
}
OUTPUT:
SERVER
CLIENT
RESULT
Thus the java program to demonstrate the ECHO command has been
executed and verified successfully.
VIVA QUESTIONS
AIM
To write a program in java to perform file transfer using TCP.
ALGORITHM
SERVER
1. Start the program.
2. Import java.net and other necessary packages.
3. Create objects for ServerSocket and Socket to send the packet
from server.
4. Using BufferedReader get the input file from client.
5. Check whether the received file name exist
6. If the file exist, read the file and send it to client.
7. Else, print file does not exist.
8. Stop the program.
CLIENT
1. Start the program.
2. Import java.net and other necessary Packages.
3. Create objects for Socket and BufferedReader .
4. Get the user input as text file name
5. Send the file name to the server through the println method
6. Using Readline method, read the contents of the file until a null is
encountered.
7. Print the received message.
8. Stop the program.
PROGRAM
CLIENT:
import java.io.*;
import java.net.*;
import java.util.*;
public class FileClient
{
public static void main(String args[])throws IOException
{
try
{
Socket soc = new Socket(InetAddress.getLocalHost(), 1187);
BufferedReader br = new BufferedReader(new
InputStreamReader(soc.getInputStream()));
PrintStream ps = new PrintStream(soc.getOutputStream());
Scanner s=new Scanner(System.in);
String input;
System.out.println("Enter the text file name");
String fileName = s.nextLine();
ps.println(fileName);
while((input = br.readLine()) != null)
{
System.out.println(input);
}
System.out.println("The file is Received successfully");
soc.close();
}
catch(Exception e)
{
System.out.println("Error: " + e);
}
}
}
SERVER :
import java.io.*;
import java.net.*;
public class FileServer
{
public static void main(String args[])throws IOException
{
try
{
ServerSocket sersoc = new ServerSocket(1187);
Socket soc = sersoc.accept();
BufferedReader br = new BufferedReader(new
InputStreamReader(soc.getInputStream()));
PrintStream ps = new PrintStream(soc.getOutputStream());
CLIENT
RESULT
Thus the java program for talk command is executed and verified
successfully.
VIVA QUESTIONS
1. Define FTProgram.
The FTP (file transfer program) utility is used to transfer files
between a local machine and remote network machine using the File
Transfer protocol.
2. In which operating systems does FTP works.
Files can be transferred between unix systems and also non-unix
systems like windows operating system using FTP.
3. Expand FTP.
File Transfer Protocol.
4. What is the port number used by FTP.
Port number 21 is used by FTP protocol.
5. What is the role of FTP.
The File Transfer Protocol (FTP) is used to connect to remote
computers, list shared files, and either upload or download files between
local and remote computers.
6. What are the advantages of FTP?
FTP runs over TCP, which provides a connection-oriented, guaranteed
data-delivery service. FTP is a character-based command interface,
although many FTP applications have graphical interfaces.
AIM
To write a program in java to perform one way message transfer using
the User Datagram Protocol (UDP).
ALGORITHM
SERVER
1. Start the program.
2. Import java.net and other necessary packages.
3. Create objects for DatagramSocket and DatagramPacket to send the
packet from server.
4. Create an object for the class byte.
5. Get user input data and convert it into bytes and send the bytes using
DatagramPacket and DatagramSocket.
6. Get user input in a loop and send data until the user input sends “end”.
7. If end is encountered, exit sending data.
8. Stop the program.
CLIENT
1. Start the program.
1. Import java.net and other necessary Packages.
2. Create objects for DatagramSocket and Datagrampacket to receive the
packet data from server.
3. Create an object for byte class.
4. Receive the data from sender using receive() method and store it to a
string.
5. Receive method receives the data from the server
6. Run a loop and store the data in the string until the received message
is “end”.
7. Print the received message.
8. Stop the program.
PROGRAM
CLIENT:
import java.io.*;
import java.net.*;
class UdpOneWayChatClient
{
public static void main(String args[])throws Exception
{
DatagramSocket ds = new DatagramSocket(8000);
DatagramPacket dp;
byte buff[] = new byte[1024];
String str;
while(true)
{
dp = new DatagramPacket(buff, buff.length);
ds.receive(dp);
str = new String (dp.getData(),0, dp.getLength());
System.out.println("Server: " + str);
}
}
}
SERVER :
import java.io.*;
import java.net.*;
import java.util.*;
class UdpOneWayChatServer
{
public static void main(String args[ ])throws IOException
{
DatagramSocket ds = new DatagramSocket();
DatagramPacket dp;
byte buff[] = new byte[1024];
String str;
Scanner s=new Scanner(System.in);
while(true)
{
System.out.print("Server:");
str = s.nextLine();
buff = str.getBytes();
CLIENT
RESULT:
Thus the java program to perform one way message transfer using the
User Datagram Protocol (UDP).
AIM
To write a java program to perform two way message transfer using the
user datagram protocol(UDP).
ALGORITHM
SERVER
1. Start the program.
2. Import java.net and other necessary packages.
3. Create objects for DatagramSocket and DatagramPacket to receive
packet data from client.
4. Create an object for InetAddress of the LocalHost.
5. Receive the client data using receive() method and store it in a string.
6. Run a loop and store the data in the string until the received message
is “end”.
7. Print the received client’s message.
8. Get user input in the same loop and send the data until the user input
is “end”.
9. Convert the user input into bytes and send the byte using
DatagramPacket and DatagramSocket.
10. If end is encountered, exit the sending data to client.
11. Stop the program.
CLIENT
1. Start the program.
2. Import java.net and other necessary packages.
3. Create objects for DatagramSocket and DatagramPacket to receive
packet data from server.
4. Create an object for InetAddress of the LocalHost.
5. Receive the server data using receive() method and store it in a string.
6. Run a loop and store the data in the string until the received message
is “end”.
7. Print the received server’s message.
8. Get user input in the same loop and send data until the user input is
end.
9. Convert the user input into bytes and send the byte using
DatagramPacket and DatagramSocket.
10. If end is encountered, exit sending data to server.
11. Stop the program.
SOURCE CODE
SERVER
import java.io.*;
import java.net.*;
import java.util.*;
class UdpTwoWayChatServer
{
public static void main(String a[])throws Exception
{
//Creates an object for Datagram socket
DatagramSocket ds = new DatagramSocket();
DatagramPacket dp, dp1;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
Scanner s=new Scanner(System.in);
String msg, msg1;
byte sendbuff[] = new byte[1024];
while(true)
{
System.out.print("Server: ");
msg = s.nextLine();
//converts message into bytes
sendbuff = msg.getBytes();
dp = new DatagramPacket(sendbuff, sendbuff.length,
InetAddress.getLocalHost(), 8000);
//send method sends data
ds.send(dp);
byte recbuff[] = new byte[1024];
dp1 = new DatagramPacket(recbuff, recbuff.length);
//receive method receives data
ds.receive(dp1);
msg1 = new String (dp1.getData(), 0, dp1.getLength());
System.out.println("Client:" + msg1);
}
}
}
CLIENT
import java.io.*;
import java.net.*;
import java.lang.*;
import java.util.*;
class UdpTwoWayChatClient
{
public static void main(String a[])throws IOException
{
//Creates an object for Datagram socket
DatagramSocket ds=new DatagramSocket(8000);
DatagramPacket dp, dp1;
Scanner s=new Scanner(System.in);
byte b[] = new byte[1024];
String msg, msg1;
while(true)
{
dp = new DatagramPacket(b, b.length);
ds.receive(dp);
msg = new String (dp.getData(), 0, dp.getLength());
System.out.println("Server: " + msg);
System.out.print("Client: ");
msg1 = s.nextLine();
byte b1[] = msg1.getBytes();
dp1 = new DatagramPacket(b1, b1.length, dp.getAddress(),
dp.getPort());
ds.send(dp1);
}
}
}
OUTPUT:
SERVER
CLIENT
RESULT
Thus the java program to perform two way message transfer using the
User Datagram Protocol (UDP).
AIM:
To implement a DNS server and client in java using UDP sockets.
ALGORITHM:
Program
import java.net.*;
public class Dns
{
public static void main(String args[]) throws UnknownHostException
{
InetAddress ipAddress = InetAddress.getLocalHost();
System.out.println(ipAddress);
ipAddress = InetAddress.getByName("www.google.com");
System.out.println(ipAddress);
ipAddress = InetAddress.getByName("www.mvit.edu.in");
System.out.println(ipAddress);
}
}
OUTPUT:
RESULT
Thus domain name requests by the client are resolved into their respective
logical address using lookup method.
VIVA QUESTIONS
1. Expand UDP
User Datagram Protocol
2. What is the difference between TCP and UDP?
TCP is connection oriented – once a connection is established, data
can be sent bidirectional.
UDP is a simpler, connectionless Internet protocol. Multiple messages
are sent as packets in chunks using UDP.
3. What form of communication does UDP represent ?
Datagram communication
4. Can you give few instances where UDP is used?
UDP is suitable for applications that need fast, efficient transmission,
such as games. UDP's stateless nature is also useful for servers that answer
small queries from huge numbers of clients.
5. Give Examples for UDP
DNS, DHCP, TFTP, SNMP, RIP, VOIP.
6. What are the applications of UDP?
UDP is commonly used in Domain Name System, Voice over IP, Trivial
File Transfer Protocol and online games.
AIM
To write a program in java to demonstrate the usage of PING command.
ALGORITHM
PINGSERVER
1.Start the program.
2. Import java.net and other necessary packages.
3. In a try block, create objects for server and client sockets .
4. Inputstream and Outputstream methods , gets data and transmits data to
the client
5. The for loop limits the number of times the server is pinged by the client.
6. If an exception occurs , the control is transferred to the catch block.
PINGCLIENT
1. Start the program.
2. Import java.net and other necessary packages.
3. Create the necessary socket
4. In a try block, get the user input as ip address
5. Inputstream and Outputstream methods ,gets data from the server and
transmits data to the server
6. If a connection exists with the server ,then a msg is displayed as
“Pinging”
7. Within a for loop, sleep method is used for 2000 ms to wait for a reply
from server.
8. If receiver is pinged, then a reply message is received within the
specified time .
9. Else, Request timed out message occurs
10. Socket is closed
SOURCE CODE
PING SERVER
import java.io.*;
import java.net.*;
public class PingServer
{
public static void main(String a[]) throws IOException
{
String line1, line2;
int i;
System.out.println("Ping Server");
try
{
ServerSocket sersoc = new ServerSocket(9999);
Socket soc = sersoc.accept();
BufferedReader br = new BufferedReader(new
InputStreamReader(soc.getInputStream()));
PrintStream ps = new PrintStream(soc.getOutputStream());
for(i = 0; i < 4; i++)
{
line1 = br.readLine();
System.out.println("Pinged by client");
ps.println(line1 + " reply from host:bytes=3<time<1ms TT<=128");
}
}
catch(Exception e)
{
System.out.println("Error: " + e);
}
}
}
PING CLIENT
import java.lang.System;
import java.io.*;
import java.net.*;
public class PingClient
{
public static void main(String args[])
{
int i, j;
String remoteIP;
try
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the IP address: ");
String ip = br.readLine();
Socket soc = new Socket(ip, 9999);
BufferedReader mybr = new BufferedReader(new
InputStreamReader(soc.getInputStream()));
PrintStream ps = new PrintStream(soc.getOutputStream());
System.out.println("Pinging " + ip + " with 32 bytes of data");
for (i = 0; i < 4; i++)
{
ps.println(ip);
ps.flush();
remoteIP = mybr.readLine();
if (remoteIP != null)
{
Thread.sleep(2000);
System.out.println("Reply from " + remoteIP);
}
else
{
for (i = 0; i < 4; i++)
{
Thread.sleep(2000);
System.out.println("Request time out");
}
}
}
soc.close();
ps.close();
}
catch (IOException e)
{
System.out.println("Error: " + e);
}
catch(InterruptedException e)
{
System.out.println(e);
}
}
}
OUTPUT:
SERVER
CLIENT
RESULT
VIVA QUESTIONS
1. What is the Ping Command?
The ping command is a Command Prompt command used to test the
ability of the source computer to reach a specified destination computer. The
ping command is usually used as a simple way verify that a computer can
communicate over the network with another computer or network device.
Ping 192.168.1.22
Ping www.google.com
AIM
To write a program in java to demonstrate the use of TALK command.
ALGORITHM
SERVER
1. Start the program.
2. Create server and client sockets.
3. Use input streams to get the message from user.
4. Use output stream to send message to the client.
5. Using while loop ,send the message to the client and also receive
message using println.
6. Stop the program.
CLIENT
1. Start the program.
2. Create a client socket that connects to the required host and port.
3. Input streams read message given by server and print it.
4. Output streams to write message to the server.
5. Using while loop , send the message to the server and also receive
message using println.
6. Stop the program.
SOURCE CODE
TALK SERVER
import java.io.*;
import java.net.*;
public class TalkServer
{
public static void main (String args[]) throws Exception
{
ServerSocket sersoc = new ServerSocket(9999);
Socket soc = sersoc.accept();
BufferedReader socbf = new BufferedReader(new
InputStreamReader(soc.getInputStream()));
PrintStream ps = new PrintStream(soc.getOutputStream());
BufferedReader bf = new BufferedReader(new
InputStreamReader(System.in));
String line1, line2;
while(true)
{
line1 = socbf.readLine();
System.out.println("Message Received: " + line1);
line2 = bf.readLine();
ps.println(line2);
ps.flush();
}
}
}
TALK CLIENT
import java.io.*;
import java.net.*;
public class TalkClient
{
public static void main(String args[])
{
String line1;
try
{
Socket soc = new Socket("LocalHost", 9999);
OUTPUT:
TALK SERVER
TALK CLIENT
RESULT :
Thus the java program for talk command is executed and verified
successfully.
AIM
To write a program in java to illustrate Remote Method Invocation.
ALGORITHM
1. Start the program.
2. Establish the connection between the client and the server to calculate
the factorial operation.
3. In the interface file, the fact method is declared.
4. In the implementation file, the fact() is defined ,which performs the
actual factorial operation.
5. In the server, the try block calls the implementation file which
indicates that the server is ready for execution.
6. In the client ,URL or the name of the host has been specified and
declared as string.
7. User input is also obtained in the client end.
8. The client program also calls the fact() in the implement() file .
9. The result is displayed
Note:
1.Create four files interface,implementation,server and client in separate
notepads.
2. During exection, compile the interface and implementations first and then the
server and client.
3.After compiling the server, start the rmiregistry .
SOURCE CODE
INTERFACE
import java.rmi.*;
import java.rmi.server.*;
public interface FactInterface extends Remote
{
public int fact (int n) throws RemoteException;
}
IMPLEMENTATION
import java.rmi.*;
import java.rmi.server.*;
SERVER
import java.rmi.*;
import java.net.*;
// start rmiregistry (in command prompt)
public class RmiServer
{
public static void main(String args[]) throws RemoteException
{
try
{
System.out.println("Enter a number:");
int n = Integer.parseInt(br.readLine());
OUTPUT
SERVER
CLIENT
RESULT
Thus the java program is executed and output is verified successfully.
AIM:
To implement simple calculator on a remote host and invoke operations
from a client.
ALGORITHM:
Interface:
Declare server's remote interface for all calculator operation by extending
Remote interface
Implementation:
Define basic calculator operations such as summation, difference,
product, quotient and
remainder by extending UnicastRemoteObject.
Server:
1. Create a calculator object
2. Register the object with the RMI registry on the server machine using rebind
method
Client
1. Obtain operands from the user
2. Lookup for the Calculator service on the remote server
3. Call all arithmetic operations on the remote server
4. Display result of various arithmetic operations.
Procedure
1. Compile the four java files (Interface, Implementation, Server and Client)
2. Generate stub by compiling the implementation file using RMI compiler
3. Distribute the class files of Client, Interface and Stub to the clients
4. Start the RMI registry on the server
5. Start the server
6. Call procedures that exist on the remote host from client machine.
PROGRAM:
// Declares remote method interfaces--CalcInf.java
import java.rmi.*;
public interface CalcInf extends Remote
{
public long add(int a, int b) throws RemoteException;
public int sub(int a, int b) throws RemoteException;
public long mul(int a, int b) throws RemoteException;
public int div(int a, int b) throws RemoteException;
public int rem(int a, int b) throws RemoteException;
}
{
public static void main(String args[])
{
try
{
CalcInf C = new CalcImpl();
Naming.rebind("CalcService", C);
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
}
// Client that invokes remote host methods--CalcClient.java
import java.rmi.*;
import java.net.*;
public class CalcClient
{
public static void main(String[] args) throws Exception
{
try
{
CalcInf C = (CalcInf) Naming.lookup("rmi://" +
args[0] + "/CalcService");
int a, b;
if (args.length != 3)
{
System.out.println("Usage: java CalcClient
<remoteip><operand1><operand2>");
System.exit(-1);
}
a = Integer.parseInt(args[1]);
b = Integer.parseInt(args[2]);
System.out.println( "\nBasic Remote Calc\n" );
System.out.println("Summation : " + C.add(a, b));
System.out.println("Difference : " + C.sub(a, b));
System.out.println("Product : " + C.mul(a, b));
System.out.println("Quotient : " + C.div(a, b));
OUTPUT
Server
C:\>javac CalcInf.java
C:\>javac CalcImpl.java
C:\>javac CalcServer.java
C:\>javac CalcClient.java
C:\>rmic CalcImpl
C:\>start rmiregistry
C:\>java CalcServer
Client
C:\>java CalcClient 172.16.6.45 6 8
Basic Remote Calc
Summation : 14
Difference : 2
Product : 48
Quotient : 0
Remainder : 6
RESULT
Thus remote procedure calls for basic operations of a calculator is executed
using Java RMI.
VIVA QUESTIONS
1. Define RMI.
5. Define Rmiregistry.
Remote objects are listed in the rmiregistry. Clients will get a reference
to the remote object by querying the rmiregistry. After that, the client can
call methods on the remote objects. The rmiregistry is a separate process
that has to be started before remote objects can be added to it
6. Expand RCE.
RCE – Remote Command Execution
7. Define RCE.
RCE is a command that enables certain commands to be xecuted from
a remote system. Eg: Notepad ,calculator can be accessed from a
remote system.
AIM
To perform remote command execution (ie) command entered by the user
at the client should be executed by the server.
ALGORITHM
SERVER
1. Start the program.
2. Create server and client socket.
3. Create a runtime object using get Runtime() method.
4. Create a process object p.
5. Read the command entered by the user at the client using input
streams.
6. Execute the command using the exec ().
7. Stop the program.
CLIENT
1. Start the program.
2. Create a client socket corresponding to the required server and port.
3. Promote the user to enter the command.
4. Read the command using input streams.
5. Write the command to the server using output streams.
6. Close the streams and socket.
7. Stop the program.
PROGRAM
CLIENT:
import java.io.*;
import java.net.*;
public class RCEclient
{
public static void main(String a[])throws UnknownHostException,IOException
{
Socket c = new Socket("localhost",1000);
System.out.println("Enter cmd:");
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String s = br.readLine();
PrintStream ps = new PrintStream(c.getOutputStream());
ps.println(s);
}
}
SERVER :
import java.io.*;
import java.net.*;
import java.lang.*;
class RCEserver
{
public static void main(String a[])throws IOException,
UnknownHostException, InterruptedException
{
ServerSocket ss = new ServerSocket(1000);
Socket cs = ss.accept();
Runtime r = Runtime.getRuntime();
Process p = null;
BufferedReader br = new BufferedReader(new
InputStreamReader(cs.getInputStream()));
String s = br.readLine();
System.out.println(s);
p = r.exec(s);
}
}
OUTPUT
SERVER
CLIENT
RESULT
Thus the java program to execute RCE is verified successfully.
SENDING DATA
Once the nodes are constructed we can have process of transmitting from
node 0 to node 1.
0
D C
In this simple example, there are two parallel TCP sessions sharing a single bottleneck link
between node 1 and node 2 (of capacity 700kb).
# Create a dumbbell topology
$ns duplex-link $s(0) $n(0) 1Mb 5ms DropTail
$ns duplex-link $s(1) $n(0) 1Mb 5ms DropTail
# Create sessions
proc build-fore-tcp { idx size intv stime } {
global ns ftcp fsink
set ftcp($idx) [new Agent/TCP/Newreno]
set fsink($idx) [new Agent/TCPSink]
$ns at $stime "start-conn 1 $idx $intv $size"
}
As a result, all packets between node 4 and node 6 are colored in red:
For flows of size bigger than 5, the first 5 packets are colored in red, and
the remaining packets are colored in blue:
command.)
exit 0
}
#create four nodes
set n0 [$ns node]
set n1 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
#create links between the nodes
$ns duplex-link $n0 & $n2 2mb 10ms Droptail
$ns duplex-link $n1 & $n2 2mb 10ms Droptail
$ns duplex-link $n2 & $n3 2mb 10ms Droptail
#set queue – limit size of link (n2-n3) to 10
$ns queue–limit $n2 $n3 10
#Give node position (for NAM)
$ns duplex – link –op $n2 orient right-down
$ns duplex – link – op $n1 orient right-up
$ns duplex – link – op $n2 $n3 orient right
#Monitor the queue for link (n2-n3) (for NAM)
$ns duplex-link-op $n2 $n3 queue-pos 0.5
#Setup a TCP connection.
set tcp [new Agent/TCP]
$tcp set class 2
$ns attach-agent $n0 $tcp
set sink [ new Agent/TCP sink]
$ ns attach-agent $n3 $sink
$ ns connect $tcp $sink
#Setup a FTP over TCP connection
set ftp [new Application / FTP]
$ftp attach-agent $tcp
#Setup a FTP connection for particular time period.
$ns at <time> “$ftp start” # (start the FTP traffic generation)
$ns at <time> “$ftp stop” # (stop the FTP traffic generation)
Running NS2
A OTcl script is generally composed as follows:
Create a new simulator object
Turn on tracing
Create network (physical layer)
Create link and queue (data-link layer)
Define routing protocol
Create transport connection (transport layer)
Create traffic (application layer)
Insert errors
The overall simulation procedure in the NS is shown below. NS is composed of
OTcl (Object-oriented Tool Command Language) Script and Interpreter. NS
simulation results can be observed through graphs by analyzing the trace file or
viewing animations with NAM.
After successful installation, path setting and validation, execute NS2 programs.
$ ns filename.tcl
RESULT
ALGORITHM:
Step 1: Start network simulator OTCL editor.
Step 2: Create new simulator using set ns [new Simulator] syntax
Step 3: Create Trace route to Network Animator set nf [open out.nam w] $ns namtrace-all
$nf
Step 4: Create procedure to trace all path
proc create_testnet {}
{
global s1 s2 r1 k1
set s1 [$ns node]
set s2 [$ns node]
set r1 [$ns node]
set k1 [$ns node]
}
Step 5: Create full duplex connection using
$ns duplex-link $n0 $n2 2Mb 10ms DropTail
$ns duplex-link $n1 $n2 2Mb 10ms RED
$ns duplex-link $n2 $n3 1.7Mb 20ms RED
$ns duplex-link $n4 $n5 2Mb 10ms RED
$ns duplex-link $n2 $n8 2Mb 10ms RED
$ns duplex-link $n4 $n10 2Mb 5ms DropTail
Step 4: #Define a 'finish' procedure
Step 5: Run and Execute the program.
$ns run
PROGRAM:
#Create a simulator object
set ns [new Simulator]
#Open the NAM trace file
set nf [open o.nam w]
$ns namtrace-all $nf
# create nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
set n7 [$ns node]
set n8 [$ns node]
set n10 [$ns node]
#Create links between the nodes
$ns duplex-link $n0 $n2 2Mb 10ms DropTail
$ns duplex-link $n1 $n2 2Mb 10ms RED
$ns duplex-link $n2 $n3 1.7Mb 20ms RED
$ns duplex-link $n4 $n5 2Mb 10ms RED
$ns duplex-link $n2 $n8 2Mb 10ms RED
$ns duplex-link $n4 $n10 2Mb 5ms DropTail
#Define a 'finish' procedure
proc finish {} {
global ns nf
$ns flush-trace
#Close the NAM trace file
close $nf
#Execute NAM on the trace file
exec nam o.nam &
exit 0
}
#Call the finish procedure
$ns at 1.0 "finish"
#Run the simulation
$ns run
OUTPUT:
\
Ex.No: 18 PERFORMANCE COMPARISONS OF MAC PROTOCOLS
ALGORITHM:
PROGRAM:
#Create a simulator object
set ns [new Simulator]
#Define different colors for data flows (for NAM)
$ns color 1 Blue
$ns color 2 Red
#Open the NAM trace file
set nf [open out.nam w]
$ns namtrace-all $nf
#Define a 'finish' procedure
proc finish {} {
global ns nf
$ns flush-trace
#Close the NAM trace file
close $nf
#Execute NAM on the trace file
exec nam out.nam &
exit 0
}
#Create four nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
#Create links between the nodes
$ns duplex-link $n0 $n2 2Mb 10ms DropTail
$ns duplex-link $n1 $n2 2Mb 10ms DropTail
$ns duplex-link $n2 $n3 1.7Mb 20ms DropTail
#Set Queue Size of link (n2-n3) to 10
$ns queue-limit $n2 $n3 10
RESULT: Thus the MAC Protocols performance compared by using NS-2 and output verified by
using Network Animator.
Aim:
To write a program to show the distance Vector Routing algorithm using NS 2
Algorithm:
1. Start the program
2. Create a simulator object
3. Use distance vector routing
4. Open the nam trace file
5. Define 'finish' procedure
6. Close the trace file
7. Execute nam on the trace file
8. Create 8 nodes
9. Specify link characteristics
10. specify layout as a octagon
11. Create a UDP agent and attach it to node n1
12. Create a CBR traffic source and attach it to udp0
13. Create a Null agent (a traffic sink) and attach it to node n4
14. Connect the traffic source with the traffic sink
15. Schedule events for the CBR agent and the network dynamics
16. Call the finish procedure after 5 seconds of simulation time
17. Run the simulation
18. Stop the program
Program
Output
$ ns distvect.tcl
RESULT
Thus implemented the program of distance Vector Routing algorithm using NS 2
Viva Voce:
1. What Is Simulation?
INTRODUCTION:
TCP
TCP Transport layer is made for process to process delivery, it deliver
packets from one process to another. Transmission Control Protocol (TCP) is a
connection oriented point-to-point protocol. It creates a virtual connection
between two TCPs to send data. It also uses flow and error control mechanism
at transport level. It is extensively used in the Internet.
UDP
User Datagram Protocol (UDP) is used as a transport layer protocol for
transfer of data across Internet Protocol based network. The protocol uses
datagrams to deliver the data. UDP is different in many ways with TCP. As TCP
is connection oriented protocol where it set up a connection first then transfer
data and terminate the connection, but in UDP there is no connection
establishment between sender and receiver. The messages are broken into
datagrams and send across the network. Each packet act as an individual
message and is handled separately. Since each datagram has to keep more
information than a TCP packet, the size of data it can carry is considerably low
as compared to TCP. All the datagrams can follow any path to reach to the
destination and hence the order in which they reach is not fixed. Neither the
sender sends any acknowledgement to the sender that the datagram is
received. Hence this protocol is considered as unreliable as it does not
guarantee that the whole data reached to the destination or not. While these
were some demerits with UDP yet it is used in various applications where some
data loss is tolerable like multimedia. Since in UDP there is no
acknowledgement service hence the network has lower overhead and hence a
better throughput and thus is faster than TCP which is suitable for the
applications like multimedia.
Performance of TCP
Bandwidth Limitation
Wireless wide area networks offer limited raw bit rates which have to be
shared between several users whereas wireless LAN offers sufficient bandwidth
Longer Latency Delay
Wireless media exhibit longer latency delays than wired ones, this affects
TCP throughput and increases the interactive delays perceived by the user.
Vulnerable Transmission Losses
Transmission losses are more in wireless media, so there is a need to find
a solution which aims at alleviating this deficiency.
User mobility
Wireless networks enable the user to move around. hosts. When a host is
moving from one cell to another handoff (or must be followed. During a handoff,
all necessary information must be transferred between the two base stations so
that the mobile host can continue to be connected. TCP exhibits Limited
bandwidth and longer latency delay in wireless networks and transmission
errors are also more in wireless media, also when there are mobile nodes, the
user mobility is a bigger concern. So there it would be beneficial to study the
TCP behavior in a hybrid network rather than in wireless network or wired
network as both have its pros and cons.
Performance of UDP
Performance of UDP in wireless networks for any closed wired network,
the nature of the connections, the number of nodes and location of the
recipients, what each needs to get from the transmission, and the response
time of each node is UDP`s performance can be best. Some researches have
found that packet drop is more in UDP protocol as compared to TCP in a
wireless network. Transmission speed also more in UDP. The behavior of UDP
in wired network and wireless network is mixed so there is a need to study the
behavior of UDP in a hybrid network where it can show the mixed behavior.
Result :
It is analyzed TCP and UDP protocols in the hybrid network with Mobile
IP and analyzed some performance metrics.
VIVA VOCE:
Subnetting divides one large network into several smaller ones. It adds an
intermediate level of hierarchy in IP addressing.
3. What is IP address?
The internet address (IP address) is 32bits that uniquely and universally
defines a host or router on the internet.
The portion of the IP address that identifies the network is called netid. The
portion of the IP address that identifies the host or router on the network is
called hostid.
EX.NO 22 socket for HTTP for web page upload and download
VIVA VOCE:
3. What is HTTPS?
Hyper Text Transfer Protocol Secure sockets (HTTPS) is a protocol for
transmission of encrypted hypertext over Secure Sockets Layer.
Ex: No: 23
IMPLEMENTING A WIRELESS SENSOR NETWORK
AIM:
To simulate a wireless sensor network using NS2.
SOFTWARE REQUIREMENTS:
NS-2 Simulator
THEORY:
A wireless sensor network (WSN) consists of a large number of small sensor nodes that are
deployed in the area in which a factor is to be monitored. In wireless sensor network, energy model is
one of the optional attributes of a node. The energy model denotes the level of energy in a mobile
node. The components required for designing energy model includes initialEnergy, txPower, rxPower,
and idlePower. The “initialEnergy” represents the level of energy the node has at the initial stage of
simulation. “txPower” and “rxPower” denotes the energy consumed for transmitting and receiving the
packets. If the node is a sensor, the energy model should include a special component called
“sensePower”. It denotes the energy consumed during the sensing operation. Apart from these
components, it is important to specify the communication range (RXThresh_) and sensing range of a
node (CSThresh_). The sample 18.tcl designs a WSN in which sensor nodes are configured with
different communication and sensing range. Base Station is configured with highest communication
range. Data Transmission is established between nodes using UDP agent and CBR traffic.
ALGORITHM:
1. Create a simulator object
2. Define a setting options for wireless channel
3. Create trace file and name file
4. Setup topography object and nodes
5. Provide initial location of mobile nodes
6. Setup a UDP connection between nodes
7. Printing the window size
PROGRAM:
# Define setting options
set val(chan) Channel/WirelessChannel ;# channel type
set val(prop) Propagation/TwoRayGround ;# radio-propagation
model set val(netif) Phy/WirelessPhy ;#
network interface type
set val(mac) Mac/802_11 ;# MAC type
set val(ifq) Queue/DropTail/PriQueue;# interface queue
type set val(ll) LL ;# link layer type
set val(ant) Antenna/OmniAntenna ;# antenna
model set val(ifqlen) 50 ;# max
packet in ifq
set val(nn) 10 ;# number of
mobilenodes set val(rp) DSDV ;#
routing protocol
set val(x) 500 ;# X dimension of topography
##################################
#copy of the data
##################################
#####Attack Node
$node_(5) color Green
$ns at 10.0 "$node_(5) color Green"
$ns at 10.0 "$node_(5) label EndUser"
# Telling nodes when the simulation ends for {set i 0} {$i < $val(nn) } { incr i } {
#$ns at $val(stop) "$node_($i) reset";
#$ns at 200.25 "$node_($i) reset";
$ns at 21.25 "$node_($i) reset";
}
$ns at 0.00 "$ns trace-annotate \"Wireless Mac Ptotocol \""
$ns at 10.0 "$ns trace-annotate \" Data send in node5 to node8 \""
$ns at 10.0 "$ns trace-annotate \" Data send in node6 to node8 \""
$ns at 10.45 "$ns trace-annotate \" Data Collision \""
$ns at 12.00 "$ns trace-annotate \"Data send in node5 to node8\""
$ns at 14.00 "$ns trace-annotate \"Data send in node6 to node8\""
$ns at 21.25 "$ns trace-annotate \"End simulation\""
$ns at 21.25 "$ns nam-end-wireless 21.01"
$ns at 21.25 "stop"
$ns at 22.01 "puts \"end simulation\" ; $ns halt" proc stop {} {
global ns tracefd namtrace
$ns flush-trace close $tracefd
close $namtrace
exec nam dsdv.nam &
$ns run
exit 0
}
AIM:
To simulate a Mobile Adhoc network (MANET) using NS2.
SOFTWARE REQUIREMENTS:
Network Simulator -2
THEORY:
A mobile ad hoc network or MANET does not depend on a fixed infrastructure for its
networking operation. 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]
create-god $val(nn)
-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 run
Viva Voce:
1. Discuss issues in designing MAC protocol for adhoc-networks.
1. Bandwidth Efficiency
2. Quality of Service support
3. Synchronization
4. Hidden and Exposed Terminal Problems