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

31 CN Lab Programs

The document outlines various experiments involving networking commands and socket programming in Java. It includes algorithms and code for TCP and UDP socket implementations, such as a date and time server, chat server, and echo server. Each section describes the aim, description, algorithm, and program code, concluding with successful execution results for each experiment.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views48 pages

31 CN Lab Programs

The document outlines various experiments involving networking commands and socket programming in Java. It includes algorithms and code for TCP and UDP socket implementations, such as a date and time server, chat server, and echo server. Each section describes the aim, description, algorithm, and program code, concluding with successful execution results for each experiment.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 48

Ex. No.

1: Networking Commands with Options

AIM:
To work on networking commands with options in Windows Operating System.

ALGORITHM:
1. Start the program.
2. Open the command prompt.
3. Enter the commands along with proper options.
4. View the Command Output.

CODING:

 IPCONFIG
(ipconfig [/allcompartments] [/? | /all | /renew [adapter] | /release [adapter] | /renew6 [adapter] |
/release6 [adapter] | /flushdns | /displaydns | /registerdns | /showclassid adapter | /setclassid adapter
[classid] | /showclassid6 adapter | /setclassid6 adapter [classid] ])

 TRACERT
tracert [-d] [-h maximum_hops] [-j host-list] [-w timeout] [-R] [-S srcaddr] [-4] [-6] target_name

 PING
ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS] [-r count] [-s count] [[-j host-list] | [-k host-
list]] [-w timeout] [-R] [-S srcaddr] [-4] [-6 target_name

 ARP

 Netstat

 ROUTE
ROUTE [-f] [-p] [-4|-6] command [destination] [MASK netmask] [gateway] [METRIC metric] [IF
interface]

1
OUTPUT:

RESULT:
Thus the Network Commands with options for Windows Operating System has been
executed successfully.

2
Exp. 2. Programs using TCP Sockets

Ex. No: 2. a PROGRAM USING TCP SOCKETS DATE AND TIME SERVER

AIM:

To implement date and time display from client to server using TCP Sockets

DESCRIPTION:

TCP Server gets the system date and time and opens the server socket to read the client details.
Client send its address to the server. Then client receives the date and time from server to display.
TCP socket server client connection is opened for communication. After the date time is
displayed the server client connection is closed with its respective streams to be closed.

ALGORITHM:

Server

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

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

3. Send servers date and time to the client.

4. Read clients IP address sent by the client.

5. Display the client details.

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

7. Close all streams.

8. Close the server socket. Stop.

Client

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

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

3. Send its address to the server.

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

5. Close the input and output streams.

6. Close the client socket. Stop.

3
PROGRAM:

//TCP Date Server--tcpdateserver.java

import java.net.*;
import java.io.*;
import java.util.*;
class tcpdateserver

public static void main(String arg[])

ServerSocket ss = null;

Socket cs;

PrintStream ps;

BufferedReader dis;

String inet;

try

ss = new ServerSocket(4444);

System.out.println("Press Ctrl+C to quit");

while(true)

{
cs = ss.accept();

ps = new PrintStream(cs.getOutputStream());

Date d = new Date();

ps.println(d);

dis = new BufferedReader(new InputStreamReader(cs.getInputStream()));

inet = dis.readLine();

System.out.println("Client System/IP address is :"+ inet);

ps.close();

dis.close();

}
4
catch(IOException e)

System.out.println("The exception is :" + e);

// TCP Date Client--tcpdateclient.java

import java.net.*; import java.io.*; class tcpdateclient

public static void main (String args[])

Socket soc; BufferedReader dis; String sdate; PrintStream ps;

try

InetAddress ia = InetAddress.getLocalHost(); if (args.length ==

0) soc = new Socket(InetAddress.getLocalHost(),4444); else

soc = new Socket(InetAddress.getByName(args[0]),4444); dis = new BufferedReader(new


InputStreamReader(soc.getInputStream())); sdate=dis.readLine();

System.out.println("The date/time on server is : " +sdate); ps = new


PrintStream(soc.getOutputStream()); ps.println(ia);

ps.close();
}
catch(IOException e)

System.out.println("THE EXCEPTION is :" + e);

}}}

5
OUTPUT

Server:

$ javac tcpdateserver.java

$ java tcpdateserver Press Ctrl+C to quit

Client System/IP address is : localhost.localdomain/127.0.0.1 Client System/IP address is :


localhost.localdomain/127.0.0.1 Client:

$ javac tcpdateclient.java

$ java tcpdateclient

The date/time on server is: Wed Jul 06 07:12:03 GMT 2011

Every time when a client connects to the server, server‟s date/time will be returned to the client for
synchronization.

RESULT:

Thus the program for implementing to display date and time from client to server using TCP Sockets
was executed successfully and output verified using various samples.

6
Ex.No: 2.b Implementation of Client-Server Communication Using TCP

AIM:

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

DESCRIPTION:

TCP Clients sends request to server and server will receives the request and response with
acknowledgement. Every time client communicates with server and receive response from
it.

ALGORITHM:

Server

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

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

3. Read Client's message and display it

4. Get a message from user and send it to client

5. Repeat steps 3-4 until the client sends "end"

6. Close all streams

7. Close the server and client socket

8. Stop

Client

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

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

3. Read server's response and display it

4. Repeat steps 2-3 until chat is terminated with "end" message

5. Close all input/output streams

6. Close the client socket

7. Stop

7
PROGRAM:

//Server.java import java.io.*; import java.net.*; class Server {

public static void main(String args[]) { String data = "Networks

Lab"; try {

ServerSocket srvr = new ServerSocket(1234);


Socket skt = srvr.accept();
System.out.print("Server has connected!\n");

PrintWriter out = new PrintWriter(skt.getOutputStream(), true);


System.out.print("Sending string: '" + data + "'\n"); out.print(data);
out.close();
skt.close();

srvr.close();

catch(Exception e) {

System.out.print("Whoops! It didn't work!\n");

//Client.java import java.io.*; import java.net.*; class Client {

public static void main(String args[]) { try {

Socket skt = new Socket("localhost", 1234); BufferedReader in = new

BufferedReader(new InputStreamReader(skt.getInputStream()));

System.out.print("Received string: '");

while (!in.ready()) {} System.out.println(in.readLine()); System.out.print("'\n"); in.close();

8
OUTPUT

Server:

catch(Exception e) {

System.out.print("Whoops! It didn't work!\n");

}}}

$ javac Server.java

$ java Server

Cilent:

Server started Client connected

$ javac Client.java

$ java Client

RESULT

Thus both the client and server exchange data using TCP socket programming.

9
Ex. No: 2. c IMPLEMENTATION OF TCP/IP ECHO

AIM:

To implementation of echo client server using TCP/IP

DESCRIPTION:

TCP Server gets the message and opens the server socket to read the client details. Client send its
address to the server. Then client receives the message from server to display.

ALGORITHM

Server

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

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

3. Read the data from client.

4. Echo the data back to the client.

5. Repeat steps 4-5 until „bye‟ or „null‟ is read.

6. Close all streams.

7. Close the server socket.

8. Stop.

Client

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

2. Get input from user.

3. If equal to bye or null, then go to step 7.

4. Send user data to the server.

5. Display the data echoed by the server.

6. Repeat steps 2-4.

7. Close the input and output streams.

8. Close the client socket.

9. Stop.

10
PROGRAM:

// TCP Echo Server--tcpechoserver.java

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

public class tcpechoserver

public static void main(String[] arg) throws IOException

ServerSocket sock = null; BufferedReader fromClient = null; OutputStreamWriter toClient = null;


Socket client = null;

try

sock = new ServerSocket(4000); System.out.println("Server Ready");

client = sock.accept(); System.out.println("Client Connected"); fromClient = new


BufferedReader(new InputStreamReader(client.getInputStream()));

toClient = new OutputStreamWriter(client.getOutputStream()); String line;

while (true)

line = fromClient.readLine();

if ( (line == null) || line.equals("bye")) break;

System.out.println ("Client [ " + line + " ]"); toClient.write("Server [ "+ line +" ]\n"); toClient.flush();

fromClient.close(); toClient.close(); client.close(); sock.close();

System.out.println("Client Disconnected");

catch (IOException ioe)

System.err.println(ioe);

11
}

//TCP Echo Client--tcpechoclient.java

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

public class tcpechoclient

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

BufferedReader fromServer = null, fromUser = null; PrintWriter toServer = null;

Socket sock = null; try

if (args.length == 0)

sock = new Socket(InetAddress.getLocalHost(),4000); else

sock = new Socket(InetAddress.getByName(args[0]),4000); fromServer = new BufferedReader(new


InputStreamReader(sock.getInputStream()));

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


PrintWriter(sock.getOutputStream(),true);

String Usrmsg, Srvmsg; System.out.println("Type \"bye\" to quit"); while (true)

System.out.print("Enter msg to server : "); Usrmsg = fromUser.readLine();

if (Usrmsg==null || Usrmsg.equals("bye"))

toServer.println("bye"); break;

else toServer.println(Usrmsg);

Srvmsg = fromServer.readLine(); System.out.println(Srvmsg);

fromUser.close(); fromServer.close(); toServer.close(); sock.close();

12
catch (IOException ioe)

System.err.println(ioe);

OUTPUT

Server:

$ javac tcpechoserver.java

$ java tcpechoserver

Server Ready Client Connected Client [ hello ]

Client [ how are you ] Client [ i am fine ] Client [ ok ] Client Disconnected

Client :

$ javac tcpechoclient.java

$ java tcpechoclient Type "bye" to quit

Enter msg to server : hello Server [ hello ]

Enter msg to server : how are you Server [ how are you ]

Enter msg to server : i am fine Server [ i am fine ]

Enter msg to server : ok Server [ ok ]

Enter msg to server : bye

RESULT

Thus data from client to server is echoed back to the client to check reliability/noise level of the
channel.

13
Ex. No.3: Programs using UDP Sockets

Ex. No: 3.a PROGRAM USING UDP SOCKET UDP CHAT SERVER/CLIENT

AIM:
To implement a chat server and client in java using UDP sockets.

DESCRIPTION:
UDP is a connectionless protocol and the socket is created for client and server to transfer the data.
Socket connection is achieved using the port number. Domain Name System is the naming
convention that divides the Internet into logical domains identified in Internet Protocol version 4
(IPv4) as a 32-bit portion of the total address.

ALGORITHM:
Server
1. Create two ports, server port and client port.
2. Create a datagram socket and bind it to client port.
3. Create a datagram packet to receive client message.
4. Wait for client's data and accept it.
5. Read Client's message.
6. Get data from user.
7. Create a datagram packet and send message through server port.
8. Repeat steps 3-7 until the client has something to send.
9. Close the server socket.
10. Stop.

Client
1. Create two ports, server port and client port.
2. Create a datagram socket and bind it to server port.
3. Get data from user.
4. Create a datagram packet and send data with server ip address and client port.
5. Create a datagram packet to receive server message.
6. Read server's response and display it.
7. Repeat steps 3-6 until there is some text to send.
8. Close the client socket.
9. Stop.

PROGRAM

// UDP Chat Server--udpchatserver.java


import java.io.*; import java.net.*; class udpchatserver
{
public static int clientport = 8040,serverport = 8050; public static void main(String args[]) throws
Exception
{
DatagramSocket SrvSoc = new DatagramSocket(clientport); byte[] SData = new byte[1024];
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Server Ready");
while (true)
{
byte[] RData = new byte[1024];

14
DatagramPacket RPack = new DatagramPacket(RData,RData.length); SrvSoc.receive(RPack);
String Text = new String(RPack.getData()); if (Text.trim().length() == 0)
break;
System.out.println("\nFrom Client <<<" + Text ); System.out.print("Msg to Cleint : " );
String srvmsg = br.readLine();
InetAddress IPAddr = RPack.getAddress(); SData = srvmsg.getBytes();
DatagramPacket SPack = new DatagramPacket(SData,SData.length,IPAddr,
serverport); SrvSoc.send(SPack);
}
System.out.println("\nClient Quits\n"); SrvSoc.close();
}
}
// UDP Chat Client--udpchatclient.java
import java.io.*; import java.net.*; class udpchatclient
{
public static int clientport = 8040,serverport = 8050; public static void main(String args[]) throws
Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader (System.in));
DatagramSocket CliSoc = new DatagramSocket(serverport);
InetAddress IPAddr;
String Text;
if (args.length == 0)
IPAddr = InetAddress.getLocalHost(); else
IPAddr = InetAddress.getByName(args[0]); byte[] SData = new byte[1024];
System.out.println("Press Enter without text to quit"); while (true)
{
System.out.print("\nEnter text for server : "); Text = br.readLine();
SData = Text.getBytes();
DatagramPacket SPack = new DatagramPacket(SData,SData.length, IPAddr, clientport
); CliSoc.send(SPack);
if (Text.trim().length() == 0) break;
byte[] RData = new byte[1024];
DatagramPacket RPack = new DatagramPacket(RData,RData.length); CliSoc.receive(RPack);
String Echo = new String(RPack.getData()) ; Echo = Echo.trim();
System.out.println("From Server <<<" + Echo);
}
CliSoc.close();
}
}

15
OUTPUT

Server
$ javac udpchatserver.java
$ java udpchatserver Server Ready
From Client <<< are u the SERVER Msg to Cleint : yes
From Client <<< what do u have to serve Msg to Cleint : no eatables
Client Quits

Client
$ javac udpchatclient.java$ java udpchatclient Press Enter without text to quit
Enter text for server : are u the SERVER From Server <<< yes
Enter text for server : what do u have to serve From Server <<< no eatables
Enter text for server : Ok

RESULT

Thus both the client and server exchange data using UDP sockets.

16
Ex.No:3.b DNS SERVER TO RESOLVE A GIVEN HOST NAME

AIM:
To develop a client that contacts a given DNS server to resolve a given hostname.

DESCRIPTION:
• Get the host name to be resolve using gethostname()
• Check the host name using nslookup
• Print the IP address, host name, Address length and Address type.
• List the addresses stored in lookup

ALGORITHM
Step 1. Find the host name by using gethostbyname()
Step 2. The host name is followed by the list of alias names
Step 3. Pointer points to the array of pointers to the individual address Step 4. For each address call
the inet_ntop() and print the returned string

PROGRAM
#include<stdio.h> #include<netdb.h> #include<arpa/inet.h> #include<netinet/in.h>
int main(int argc,char**argv)
{
char h_name; int h_type;
struct hostent *host; struct in_addr h_addr; if(argc!=2)
{
fprintf(stderr,"USAGE:nslookup\n");
}
if((host=gethostbyname(argv[1]))==NULL)
{
fprintf(stderr,"(mini)nslookup failed on %s\n",argv[1]);
}
h_addr.s_addr=*((unsigned long*)host->h_addr_list[0]); printf("\n IP ADDRESS=%s\
n",inet_ntoa(h_addr)); printf("\n HOST NAME=%s\n",host->h_name); printf("\nADDRESS LENGTH
=%d\n",host->h_length); printf("\nADDRESS TYPE=%d\n",host-
>h_addrtype);
printf("\nLIST OF ADDRESS=%s\n",inet_ntoa(h_addr_list[0]));
}

OUTPUT
[it28@localhost ~]$ vi dns.c [it28@localhost ~]$ cc dns.c [it28@localhost ~]$ ./a.out 90.0.0.36
IP ADDRESS=90.0.0.36
HOST NAME=90.0.0.36 ADDRESS LENGTH =4 ADDRESS TYPE=2
LIST OF ADDRESS=90.0.0.36

RESULT
Hence the program to develop a client that contacts a given DNS server to resolve a given
host name is executed successfully.

17
Ex No: 3.c UDP DNS SERVER/CLIENT

AIM:
To implement a DNS server and client in java using UDP sockets.

DESCRIPTION
DNS stands for domain name system. unique name of the host is identified with its IP address
through server client communication.

ALGORITHM:
Server
1. Create an array of hosts and its ip address in another array
2. Create a datagram socket and bind it to a port
3. Create a datagram packet to receive client request
4. Read the domain name from client to be resolved
5. Lookup the host array for the domain name
6. If found then retrieve corresponding address
7. Create a datagram packet and send ip address to client
8. Repeat steps 3-7 to resolve further requests from clients
9. Close the server socket
10. Stop
Client
1. Create a datagram socket
2. Get domain name from user
3. Create a datagram packet and send domain name to the server
4. Create a datagram packet to receive server message5. Read server's response
5. If ip address then display it else display "Domain does not exist"
6. Close the client socket
7. Stop

PROGRAM
// UDP DNS Server -- udpdnsserver.java
import java.io.*; import java.net.*;
public class udpdnsserver
{
private static int indexOf(String[] array, String str)
{
str = str.trim();
for (int i=0; i < array.length; i++)
{
if (array[i].equals(str)) return i;
}
return -1;
}
public static void main(String arg[])throws IOException
{
String[] hosts = {"yahoo.com", "gmail.com","cricinfo.com", "facebook.com"}; String[] ip =
{"68.180.206.184", "209.85.148.19","80.168.92.140",
"69.63.189.16"};

18
System.out.println("Press Ctrl + C to Quit"); while (true)
{
DatagramSocket serversocket=new DatagramSocket(1362); byte[] senddata = new byte[1021];
byte[] receivedata = new byte[1021]; DatagramPacket recvpack = new DatagramPacket(receivedata,
receivedata.length); serversocket.receive(recvpack);
String sen = new String(recvpack.getData()); InetAddress ipaddress = recvpack.getAddress();
int port = recvpack.getPort();
String capsent;
System.out.println("Request for host " + sen);
if(indexOf (hosts, sen) != -1) capsent = ip[indexOf (hosts, sen)]; else
capsent = "Host Not Found"; senddata = capsent.getBytes();
DatagramPacket pack = new DatagramPacket(senddata, senddata.length,ipaddress,port);
serversocket.send(pack);
serversocket.close();
}
}
}
//UDP DNS Client -- udpdnsclient.java
import java.io.*; import java.net.*;
public class udpdnsclient
{
public static void main(String args[])throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); DatagramSocket
clientsocket = new DatagramSocket();
InetAddress ipaddress; if (args.length == 0)
ipaddress = InetAddress.getLocalHost(); else
ipaddress = InetAddress.getByName(args[0]); byte[] senddata = new byte[1024];
byte[] receivedata = new byte[1024]; int portaddr = 1362;
System.out.print("Enter the hostname : "); String sentence = br.readLine();
Senddata = sentence.getBytes();
DatagramPacket pack = new DatagramPacket(senddata,senddata.length, ipaddress,portaddr);
clientsocket.send(pack);
DatagramPacket recvpack =new
DatagramPacket(receivedata,receivedata.length); clientsocket.receive(recvpack);
String modified = new String(recvpack.getData()); System.out.println("IP Address: " + modified);
clientsocket.close(); }}

19
OUTPUT
Server
$ javac udpdnsserver.java
$ java udpdnsserver Press Ctrl + C to Quit
Request for host yahoo.com Request for host cricinfo.com Request for host youtube.com

Client
$ javac udpdnsclient.java
$ java udpdnsclient
Enter the hostname : yahoo.com IP Address: 68.180.206.184
$ java udpdnsclient
Enter the hostname : cricinfo.com IP Address: 80.168.92.140
$ java udpdnsclient
Enter the hostname : youtube.com IP Address: Host Not Found

RESULT

Hence the program to implement a DNS server and client in java using UDP sockets is executed
successfully.

20
Ex. No. 4: File Transfer between two computers

AIM:
To write a java program to create a Socket (TCP) between two computers and enable file transfer
between them.

ALGORITHM:
Server
Step1: Import java packages and create class file server. Step2: Create a new server socket and
bind it to the port. Step3: Accept the client connection
Step4: Get the file name and stored into the BufferedReader.
Step5: Create a new object class file and realine.
Step6: If file is exists then FileReader read the content until EOF is reached.
Step7: Stop the program.

Client

Step1: Import java packages and create class file server. Step2: Create a new server socket and
bind it to the port. Step3: Now connection is established.
Step4: The object of a BufferReader class is used for storing data content which has been retrieved
from socket object.
Step5 The connection is closed.
Step6: Stop the program.

PROGRAM
File Server:
import java.io.BufferedInputStream; import java.io.File;
import java.io.FileInputStream; import java.io.OutputStream; import java.net.InetAddress; import
java.net.ServerSocket; import java.net.Socket;
public class FileServer
{
public static void main(String[] args) throws Exception
{
//Initialize Sockets
ServerSocket ssock = new ServerSocket(5000); Socket socket = ssock.accept();
//The InetAddress specification
InetAddress IA = InetAddress.getByName("localhost");

//Specify the file


File file = new File("e:\\Bookmarks.html"); FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
//Get socket's output stream
OutputStream os = socket.getOutputStream();
//Read File Contents into contents array byte[] contents;
long fileLength = file.length(); long current = 0;
long start = System.nanoTime(); while(current!=fileLength){
int size = 10000;
if(fileLength - current >= size) current += size;
else{
size = (int)(fileLength - current); current = fileLength;
}

21
contents = new byte[size]; bis.read(contents, 0, size); os.write(contents);
System.out.print("Sending file ... "+(current*100)/fileLength+"%
complete!");
}
os.flush();
//File transfer done. Close the socket connection! socket.close();
ssock.close();
System.out.println("File sent succesfully!");
}}

File Client
import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.InputStream;
import java.net.InetAddress; import java.net.Socket;

public class FileClient {


public static void main(String[] args) throws Exception{
//Initialize socket
Socket socket = new Socket(InetAddress.getByName("localhost"), 5000); byte[] contents = new
byte[10000];
//Initialize the FileOutputStream to the output file's full path.
FileOutputStream fos = new FileOutputStream("e:\\Bookmarks1.html"); BufferedOutputStream bos
= new BufferedOutputStream(fos); InputStream is = socket.getInputStream();
//No of bytes read in one read() call int bytesRead = 0;
while((bytesRead=is.read(contents))!=-1) bos.write(contents, 0, bytesRead);
bos.flush(); socket.close();
System.out.println("File saved successfully!");
}
}

22
OUTPUT

Server
E:\nwlab>java FileServer
Sending file ... 9% complete! Sending file ... 19% complete! Sending file ... 28% complete! Sending
file ... 38% complete! Sending file ... 47% complete! Sending file ... 57% complete! Sending file ...
66% complete! Sending file ... 76% complete! Sending file ... 86% complete! Sending file ... 95%
complete!
Sending file ... 100% complete! File sent successfully!

E:\nwlab>

client

E:\nwlab>java FileClient File saved successfully!

E:\nwlab>

RESULT

Thus the java program file transfer application using TCP Sockets was executed

23
Ex. No. 5: REMOTE COMMAND EXECUTION
Aim:

Write a program to implement remote command execution.

Algorithm:

1. Create an object for the command to be executed


2. Store the result in a string & write it into a socket
3. Create a socket on the client side to receive the packets send from the other side

Program:

Server:

import java.io.*;

import java.net.*;

import java.util.*;

import java.lang.String.*;

class dateserver

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

{ int i=0;

DatagramSocket ds = new DatagramSocket(111);

byte b[] = new byte[2048];

Date serdate=new Date();

String a=new String();

a=serdate.toString();

for(i=0;i<a.length();i++)

{ b[i]=(byte)a.charAt(i); }

ds.send(new DatagramPacket(b,i,InetAddress.getByName("127.0.0.1"),2222));

}}

Receiver:

import java.io.*;

import java.net.*;

24
import java.util.*;

import java.lang.String.*;

class dateclient

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

String s=new String();

byte b[] = new byte[1024];

DatagramSocket ds = new DatagramSocket(2222);

DatagramPacket dp=new DatagramPacket(b,1024);

ds.receive(dp);

s=new

String(dp.getData(),0,0,dp.getLength());

System.out.println(s); }}

Output:

C:\nlab\remotecom>java dateserver

C:\nlab\remotecom>java dateclient

Mon Jan 08 10:27:17 PST 2007

RESULT: Thus the program is executed successfully and the output was verified.

25
Ex.No. 6: RMI – REMOTE METHOD INVOCATION

Aim:

Write a program to implement RMI (Remote Method Invocation)

Algorithm:

1. Create an Interface that needs to be implemented by the server


2. Write the serverimpl program that actually implements the process
3. Write the server which binds to the rmiregistry and makes the remote object available.
4. Now write down the client program to accept the input
5. Start the rmiregistry, server and the client program

Program:

AddServerIntf.java

import java.rmi.*;

public interface AddServerIntf extends Remote

double add(double e,double f ) throws java.rmi.RemoteException;

AddServerImpl.java
import java.rmi.*;

import

java.rmi.server.*;

public class AddServerImpl extends UnicastRemoteObject implements AddServerIntf

public AddServerImpl() throws RemoteException

public double add(double d1, double d2) throws RemoteException

return d1+d2;

}}

26
AddServer.java
import java.net.*;

import java.rmi.*;

public class AddServer

public static void main(String args[]) throws RemoteException,MalformedURLException

AddServerImpl ASI = new AddServerImpl();

Naming.rebind("AddServer",ASI);

}}

AddClient.java
import java.rmi.*;

public class AddClient

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

String URL="rmi://"+args[0]+"/AddServer";

AddServerIntf addserverintf=(AddServerIntf)

Naming.lookup(URL); double d1 =

Double.valueOf(args[1]).doubleValue();

double d2 = Double.valueOf(args[2]).doubleValue();

System.out.println("The Result Is "+addserverintf.add(d1,d2));

27
Output:

Start rmiregistry

Java AddServer

Java AddClient

2+5

RESULT: Thus the program is executed successfully and the output was verified.

28
Exp. No. 7: IMPLEMENTATION OF ADDRESS RESOLUTION PROTOCOL

AIM
To implement Address Resolution Protocol .

ALGORITHM
CLIENT SIDE
1. Establish a connection between the Client and Server.
Socket ss=new Socket(InetAddress.getLocalHost(),1100);
2. Create instance output stream writer
PrintWriter ps=new PrintWriter(s.getOutputStream(),true);
3. Get the IP Address to resolve its physical address.
4. Send the IPAddress to its output Stream.ps.println(ip);
5. Print the Physical Address received from the
server. SERVER SIDE
1. Accept the connection request by the client.
ServerSocket ss=new ServerSocket(2000);Socket s=ss.accept();
2. Get the IPaddress from its inputstream.
BufferedReader br1=new BufferedReader(newInputStreamReader(s.getInputStream()));
ip=br1.readLine();
3. During runtime execute the processRuntime
r=Runtime.getRuntime(); Process p=r.exec("arp -a "+ip);
4. Send the Physical Address to the client.

PROGRAM
ARP CLIENT
importjava.io.*;
import java.net.*;
class ArpClient
{
public static void main(String args[])throws IOException
{
try
{
Socketss=newSocket(InetAddress.getLocalHost(),1100);
PrintStream ps=new PrintStream(ss.getOutputStream());
BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));
Stringip;
System.out.println("Enter the IPADDRESS:");
23
ip=br.readLine();
ps.println(ip);
Stringstr,data;
BufferedReaderbr2=newBufferedReader(newInputStreamReader(ss.getInputStream()));
System.out.println("ARP From Server::");

29
do
{
str=br2.readLine();
System.out.println(str);
}
while(!(str.equalsIgnoreCase("end")));
}
catch(IOException e)
{
System.out.println("Error"+e);
}}}
ARP SERVER
importjava.io.*;
import java.net.*;
classArpServer
{
public static void main(String args[])throws IOException
{
try
{
ServerSocketss=newServerSocket(1100);
Sockets=ss.accept();
PrintStream ps=new PrintStream(s.getOutputStream());
BufferedReaderbr1=newBufferedReader(newInputStreamReader(s.getInputStream()));
String ip;
ip=br1.readLine();
Runtime r=Runtime.getRuntime();
Process p=r.exec("arp-a "+ip);
BufferedReaderbr2=newBufferedReader(newInputStreamReader(p.getInputStream()));
Stringstr;
while((str=br2.readLine())!=null)
{
ps.println(str);
}}
catch(IOException e)
{
System.out.println("Error"+e); }}}
24

30
OUTPUT
C:\NetworkingPrograms>javaArpServer
C:\NetworkingPrograms>javaArpClient
Enterthe IPADDRESS:
192.168.11.58
ARPFromServer::
Interface: 192.168.11.57 on Interface 0x1000003
InternetAddress PhysicalAddress Type
192.168.11.58 00-14-85-67-11-84 dynamic

RESULT
Thus the implementation of ARP is done & executed successfully.

31
Ex. No. 8: SIMULATION OF SLIDING WINDOW PROTOCOL

Aim: To write a C program to perform sliding window.

Algorithm

1. Start the program.


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

Program:

Client:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
struct mymsgbuf
{
long mtype;
char mtext[25];
};
FILE *fp;
int main()
{
struct mymsgbuf buf;
int msgid;
int i=0,s;
int count=0,frmsz;
int a[100];
char d; if((msgid=msgget(89,IPC_CREAT|
0666))==-1)
{
printf("\n ERROR IN MSGGET");
exit(0);
}
printf("\n Enter the frame size:"); scanf("%d",&frmsz);
if((fp=fopen("check","r"))==NULL) printf("\n FILE NOT OPENED");
else
printf("\n FILE OPENED");
while(!feof(fp))
{ d=getc(fp);
a[i]=d;
i++;

32
}
s=i;
for(i=0;i<frmsz;i++)
//print from the check file printf("\t %c",a[i]);
for(i=0;i<frmsz;i++)
{ if((msgrcv(msgid,&buf,sizeof(buf),0,1))==-1)
{
printf("\n ERROR IN MSGRCV");
exit(0);
}
printf("\n RECEIVED FRAMES ARE:%c",buf.mtext[i]);
}
for(i=0;i<frmsz;i++)
{ if(a[i]==buf.mtext[i])
count++;
} if(count==0)
{
printf("\n FRAMES WERE NOT RECEIVED IN CORRECT SEQ");
exit(0);
} if(count==frmsz)
{
printf("\n FRAMES WERE RECEIVED IN CORRECT SEQ");
} else
{
printf("\n FRAMES WERE NOT RECEIVED IN CORRECT SEQ");
}}

Sliding Window Protocol - Server


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
struct mymsgbuf
{ long mtype;
char mtext[25];
};
FILE *fp;
int main()
{s
truct mymsgbuf buf;
int si,ei,sz; int msgid; int i=0,s; int a[100]; char d;
if((fp=fopen("send","r"))==NULL) printf("\n FILE NOT OPENED"); else
printf("\n FILE OPENED");
printf("\n Enter starting and ending index of frame array:"); scanf("%d
%d",&si,&ei); sz=ei-si; if((msgid=msgget(89,IPC_CREAT|0666))==-1)
{
printf("\n ERROR IN MSGGET");
exit(0);
}
while(!feof(fp))
{ d=getc(fp); a[i]=d;

33
i++;
}s
=i; buf.mtype=1; for(i=si;i<=ei;i++)
{
buf.mtext[i]=a[i];
}
for(i=si;i<=ei;i++) //the frames to be sent
printf("\t %c",buf.mtext[i]); for(i=0;i<=sz;i++)
{ if((msgsnd(msgid,&buf,sizeof(buf),0))==-1)
{
printf("\n ERROR IN MSGSND");
exit(0);
}}
printf("\n FRAMES SENT");
return 0; }

OUTPUT:
Enter the frame size : 5
File opened
Enter starting & ending index of frame array : 0 9
Frames sent
Received frames are: 0 3 6 7 9

RESULT:
Thus the above program sliding window protocol was executed and successfully.

34
Exp. No. 9: WEB PAGE DOWNLOADING

AIM

To download a webpage using Java

ALGORITHM

CLIENT SIDE:

1) Start the program.

2) Create a socket which binds the Ip address of server and the port address to acquire service.

3) After establishing connection send the url to server.

4) Open a file and store the received data into the file.

5) Close the socket.

6) End the program.

SERVER SIDE

1) Start the program.

2) Create a server socket to activate the port address.

3) Create a socket for the server socket which accepts the connection.

4) After establishing connection receive url from client.

5) Download the content of the url received and send the data to client.

6) Close the socket.

7) End the program.

PROGRAM

import javax.swing.*;

import java.net.*;

import

java.awt.image.*; import

javax.imageio.*; import

java.io.*;

import java.awt.image.BufferedImage;

35
import java.io.ByteArrayOutputStream;

36
import java.io.File;

import java.io.IOException;

import javax.imageio.ImageIO;

public class Client{

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

Socket soc;

BufferedImage img = null;

soc=new Socket("localhost",4000);

System.out.println("Client is running. ");

try {

System.out.println("Reading image from disk. ");

img = ImageIO.read(new

File("digital_image_processing.jpg")); ByteArrayOutputStream

baos = new ByteArrayOutputStream(); ImageIO.write(img,

"jpg", baos);

baos.flush();

byte[] bytes = baos.toByteArray();

baos.close(); System.out.println("Sending image to server. ");

OutputStream out = soc.getOutputStream();

DataOutputStream dos = new DataOutputStream(out);

dos.writeInt(bytes.length);

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

System.out.println("Image sent to server. ");

dos.close();

out.close();

}catch (Exception e) {

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

soc.close();

37
soc.close();

38
}

SERVER PROGRAM

import java.net.*;

import java.io.*;

import java.awt.image.*;

import javax.imageio.*;

import javax.swing.*;

class Server {

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

ServerSocket server=null;

Socket socket;

server=new ServerSocket(4000);

System.out.println("Server Waiting for image");

socket=server.accept();

System.out.println("Client connected.");

InputStream in = socket.getInputStream();

DataInputStream dis = new DataInputStream(in);

int len = dis.readInt();

System.out.println("Image Size: " + len/1024 + "KB");

byte[] data = new byte[len];

dis.readFully(data);

dis.close();

in.close();

InputStream ian = new

ByteArrayInputStream(data); BufferedImage

bImage = ImageIO.read(ian); JFrame f = new

JFrame("Server");

ImageIcon icon = new ImageIcon(bImage);

39
JLabel l = new JLabel();

40
l.setIcon(icon);

f.add(l);

f.pack();

f.setVisible(true); }}

OUTPUT

RESULT

The webpage is successfully downloaded and the contents are displayed and verified.

41
Exp. No. 10: Demonstration of Network Simulators

Aim: To demonstrate the usage of Network Simulators.

NETWORK SIMULATORS:
Provides an integrated, versatile, easy-to-use GUI-based network designer tool to design and also
simulate a network with SNMP, TL1, TFTP, FTP, Telnet and also Cisco IOS device.

List of Network Simulators:


There are different network simulators which also offers different features. Some of them are:


Ns3 (Network Simulator 3).

OPNET.

OMNeT++.

NetSim.

REAL.

QualNet.

J- Ns2 (Network Simulator 2).

Sim.

Packet Tracer

NS2 (Network Simulator 2):


 It is also a discrete event simulator that provides substantial support for simulation of TCP,
routing, and also multicast protocols over wired and wireless networks..
 Also It use C++ and also OTcl languages.
 Sample ns2 code. In which there are also four different nodes are available and two different
routers.

set node(s1) [$ns


1
node] set node(s2)
[$ns node]
2set
node(r1) [$ns node]
3set node(r2) [$ns
node] 4set node(s3)
[$ns node] 5set
node(s4) [$ns node]
6$ns duplex-link $node(s1) $node(r1) 15Mb 2.5ms DropTail
7$ns duplex-link $node(s2) $node(r1) 15Mb 3.2ms
DropTail 8$ns duplex-link $node(r1) $node(r2)
2.5Mb 22ms RED 9$ns queue-limit $node(r1)
$node(r2) 28
10$ns queue-limit $node(r2) $node(r1) 28
11$ns duplex-link $node(s3) $node(r2) 15Mb 4.2ms
DropTail 12$ns duplex-link $node(s4) $node(r2) 15Mb
5ms DropTail 13$ns duplex-link-op $node(s1) $node(r1)
orient right-down $ns duplex-link-op $node(s2)
14
$node(r1) orient right-up $ns duplex-link-op
15
$node(r1) $node(r2) orient
$ns duplex-link-op right$node(r2) queuePos 0
$node(r1)
16
$ns duplex-link-op $node(r2) $node(r1) queuePos 0
17
$ns duplex-link-op $node(s3) $node(r2) orient left-down
18$ns duplex-link-op $node(s4) $node(r2) orient left-
up 19set tcp1 [$ns create-connection TCP/Reno
$node(s1) TCPSink 20$node(s3) 0]
21$tcp1 set window_ 15
42
22set tcp2 [$ns create-connection TCP/Reno $node(s2) TCPSink
23$node(s3) 1]

43
24$tcp2 set window_ 15
25set ftp1 [$tcp1 attach-source
FTP] 26set ftp2 [$tcp2 attach-
source FTP] 27$ns at 0.0 "$ftp1
start"
28$ns at 3.0 "$ftp2
start" 29$ns at 15
"finish" $ns run
30
31
32

NS3 (Network Simulator 3):


 Ns3 uses C++ and also Python languages for simulating the script.
 C++ used for implementation of simulation and also core model. Ns-3 is built as a
library which may be statically or dynamically linked to a C++ main program.
 Python: C++ wrapped by Python. Python programs also to import an “ns3” module.
 Sample code for ns3.

1
2
3int
{
main (int argc, char *argv[])
4
LogComponentEnable ("UdpEchoClientApplication",
5
LOG_LEVEL_INFO);
6LogComponentEnable ("UdpEchoServerApplication",
7LOG_LEVEL_INFO);
8RandomVariable::UseGlobalSeed (1, 1, 2, 3, 5, 8);
9NodeContainer nodes; nodes.Create (2);
10PointToPointHelper pointToPoint;
11pointToPoint.SetDeviceAttribute("DataRate",StringValue("5Mbps”));
12pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms"));
13NetDeviceContainer devices;
14devices = pointToPoint.Install (nodes);
15InternetStackHelper stack; stack.Install
(nodes); 16Ipv4AddressHelper address;
17address.SetBase ("10.1.1.0", "255.255.255.0");
18Ipv4InterfaceContainer interfaces = address.Assign (devices);
19UdpEchoServerHelper echoServer (9);
ApplicationContainer serverApps = echoServer.Install
20(nodes.Get(1)); serverApps.Start (Seconds (1.0));
21serverApps.Stop (Seconds (10.0));
22
UdpEchoClientHelper echoClient (interfaces.GetAddress (1), 9);
23echoClient.SetAttribute ("MaxPackets", UintegerValue (1));
24echoClient.SetAttribute ("Interval", TimeValue (Seconds
(1.))); 25echoClient.SetAttribute ("PacketSize", UintegerValue
(1024)); 26ApplicationContainer clientApps = echoClient.Install
(nodes.Get(0)); 27clientApps.Start (Seconds (2.0));
clientApps.Stop (Seconds (10.0)); 28Simulator::Run ();
Simulator::Destroy (); return0;}

44
OMNeT++:

45
 It is a component-based, modular and also open architecture discrete event simulator
framework.
 The most common use of OMNeT++ is also for simulation of computer networks, but it is
also used for queuing network simulations and other areas as well.
 C++ is a class library, eclipse based simulation IDE is also used for designing, running and
evaluating simulations.
 Sample code for OMNeT++

#include
&amp;amp;amp;amp;amp;amp;lt;omnetpp.h&amp;amp;amp;amp;amp;amp;gt;
1classSink: public cSimpleModule
2
3{ Module_Class_Members(Sink,
virtual void activity(); cSimpleModule, 8192);
Define_Module(Sink
};
4void
); Sink::activity()
5{ while(1)
6{ cMessage *msg = receive(); int pkt_type = msg -&amp;amp;amp;amp;amp;amp;gt;
kind(); 7if(pkt_type ==1) ev
&amp;amp;amp;amp;amp;amp;lt;&amp;amp;amp;amp;amp;amp;lt; “Received 8data packet\n”;
9elseev &amp;amp;amp;amp;amp;amp;lt;&amp;amp;amp;amp;amp;amp;lt; “Received voice
packet\n”;
10deletemsg;} }
OPNET:
 It provides a comprehensive development environment supporting the modeling of
communication networks and also distributed systems.
 Both behavior and performance of modeled systems can also analyzed by performing discrete
event simulations.
 C is a main programming language in OPNET and also use GUI for initial configurations.
The simulation scenario requires c or C++.
 Sample code for OPNET

1ifndef OMSC_EXPORT 2#define OMSC_EXPORT 3#endif


4#ifndef _OMS_DATA_DEF_H_INCL_
5#define _OMS_DATA_DEF_H_INCL_
6/* Include the database data structures. */
7#include "/home/juan/op_models/aplicaciones/oms_data_def_ds_defs.h"
8#if defined ( cplusplus)
9extern "C"{
10#endif
11/** -------- Data Structures**/

12/** ------ External Functions**/


OMSC_EXPORT void
13
oms_data_def_entry_insert (const char* category_name, const char* entry_name, void*
14entry_ds_ptr);
15OMSC_EXPORT void*
16oms_data_def_entry_access (const char* category_name, const char* entry_name);
17#if defined ( cplusplus) 18} /* end of 'extern "C" {' */ 19#endif
20#endif

QualNet:

46
 It is also a commercial network simulator from Scalable Network Technologies.
 Also It is ultra high-fidelity network simulation software that predicts wireless, wired and
mixed-platform network and also networking device performance.
 A simulator for large, heterogeneous networks and also the distributed applications that
execute on such networks.
 It use C++ for implementing new protocols and also follows a procedural paradigm.

JSIM:
 It’s also a java based simulator tool.
 Java is easy to learn and easy to use. In case of any problems, source texts provided with J-
Sim can be used to generate new code, compiled in the target environment, thus 100-percent
compatible with JVM used.
 Use java and Tcl languages.
 Sample code for JSIM.

# echoer.tcl
cd [mkdir -q drcl.comp.Component
/test] puts "create topology..."
set link_
&amp;amp;amp;amp;amp;amp;lt;pre&amp;amp;amp;amp;amp;amp;gt;&amp;amp;amp;am
p;amp;a mp;lt;/pre&amp;amp;amp;amp;amp;amp;gt;
$link_ setPropDelay 0.3;#
300ms set adjMatrix_
&amp;amp;amp;amp;amp;amp;lt;pre&amp;amp;amp;amp;amp;amp;gt;&amp;amp;amp;am
p;amp;a mp;lt;/pre&amp;amp;amp;amp;amp;amp;gt;
[]} 3 {{1} {0 2} {1}}]
java::call drcl.inet.InetUtil createTopology [! .] $adjMatrix_
$link_
puts "create builders..."
set nb [mkdir drcl.inet.NodeBuilder .nodeBuilder]
$nb setBandwidth 1.0e7; puts "build..."
$nb build [! n?]
$nb build [! h?] {
Udp
drcl.inet.transport.UDP
echo 101/udp new_echoer
}
! h?/udp setTTL 3
! n1 setBandwidth 1 1.0e4;! n1 setBufferSize 1
6000; puts "setup static routes..."
java::call drcl.inet.InetUtil setupRoutes [! h0]
[! h2] "bidirection"
puts "set up

47
NetSim:
 It has an object-oriented system modeling and simulation (M&S) environment to support
simulation and analysis of voice and data communication scenarios for High Frequency
Global Communication Systems (HFGCS).
 NetSim use java as a programming language it creates applet and linked into HTML
document for viewable on the java-compatible browser.

REAL:
 REAL is a simulator for studying the dynamic behavior of flow and congestion control
schemes in packet switch data networks.
 It provides users with a way of specifying such networks and to observe their behavior.
 REAL uses C as a programming languge.
 Sample code for REAL simulator

#include "../kernel/real.h"
ecn_dummy() { PKT_PTR pkt; int node, num_pkts_sent =
0; ident destn, sender, sink; long key; timev now;
int seq_no = 0; node =
RESULT:
get_node_id(); sink =
assigned_sink[node];
Thus the various Network Simulators has been studied.
abs_advance(node_start_time[node]); now = runtime();
if(node is 1) { make_pkt(pkt); pkt-&amp;amp;amp;amp;amp;amp;gt;dest =
sink; pkt-&amp;amp;amp;amp;amp;amp;gt;data[0] = num_pkts[node];
sendm(sink, 0, pkt); printf("Node 1 sent request packet\n");}
for(ever) { sender = recvm(&amp;amp;amp;amp;amp;amp;amp;destn,
&amp;amp;amp;amp;amp;amp;amp;key, &amp;amp;amp;amp;amp;amp;amp;pkt);
now = runtime(); switch(pkt-&amp;amp;amp;amp;amp;amp;gt;type){ caseACK:
free(pkt); break;
caseINT: free(pkt); break;
caseDATA: pkt-&amp;amp;amp;amp;amp;amp;gt;type = ACK;
pkt-&amp;amp;amp;amp;amp;amp;gt;dest = pkt-
&amp;amp;amp;amp;amp;amp;gt;source; pkt-

48

You might also like