0% found this document useful (0 votes)
8 views29 pages

PROGRAMS CN - Removed (1) - 250402 - 221024 (1) V

The document outlines various experiments involving Java programming for network communications, including simulating ping and traceroute commands, HTTP socket programming for image upload and download, implementing Remote Procedure Calls (RPC), subnetting, and applications using TCP sockets such as echo clients and servers, chat applications, and file transfers. Each experiment includes objectives, algorithms, and sample code. The document serves as a comprehensive guide for understanding and implementing network programming concepts in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views29 pages

PROGRAMS CN - Removed (1) - 250402 - 221024 (1) V

The document outlines various experiments involving Java programming for network communications, including simulating ping and traceroute commands, HTTP socket programming for image upload and download, implementing Remote Procedure Calls (RPC), subnetting, and applications using TCP sockets such as echo clients and servers, chat applications, and file transfers. Each experiment includes objectives, algorithms, and sample code. The document serves as a comprehensive guide for understanding and implementing network programming concepts in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

EXPERIMENT 4:

WRITE A CODE SIMULATING “PING” AND “TRACEROUTE” COMMANDS.

OBJECTIVE: To Write The java program for simulating ping and traceroute
commands.

Concept:

PING Command
The ping command is a very common method for troubleshooting the accessibility
of devices.
It uses a series of Internet Control Message Protocol (ICMP) Echo messages to
determine:
1. Whether a remote host is active or inactive.
2. The round-trip delay in communicating with the host.
3. Packet loss.

The ping command first sends an echo request packet to an address, and then waits
for a reply.
The ping is successful only if:
1. the echo request gets to the destination, and
2. The destination is able to get an echo reply back to the source within a
predetermined time called a timeout. The default value of this timeout is two
seconds on Cisco routers.

TRACEROUTE Command
1. The trace route command is used to discover the routes that packets actually take
when traveling to their destination. The device (for example, a router or a PC) sends
out a sequence of User Datagram Protocol (UDP) data grams to an invalid port
address at the remote host.
2. Three data grams are sent, each with a Time-To-Live (TTL) field value set to one.
The TTL value of 1 causes the datagram to "timeout" as soon as it hits the first
router in the path; this router then responds with an ICMP Time Exceeded Message
(TEM) indicating that the datagram has expired.

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:

//pingclient.java
import java.io.*;
import java.net.*;
import java.util.Calendar;
class pingclient
{
public static void main(String args[])throws Exception
{
String str;
int c=0;
long t1,t2;
Socket s=new Socket("127.0.0.1",5555);
DataInputStream dis=new DataInputStream(s.getInputStream());
PrintStream out=new PrintStream(s.getOutputStream());
while(c<4)
{
t1=System.currentTimeMillis();
str="Welcome to network programming world";
out.println(str);
System.out.println(dis.readLine());
t2=System.currentTimeMillis();
System.out.println(";TTL="+(t2-t1)+"ms");
c++;
}
s.close();
}
}
import java.io.*;
import java.net.*;
import java.util.*;
import java.text.*;
class pingserver
{
public static void main(String args[])throws Exception
{
ServerSocket ss=new ServerSocket(5555);
Socket s=ss.accept();
int c=0;
while(c<4)
{
DataInputStream dis=new DataInputStream(s.getInputStream());
PrintStream out=new PrintStream(s.getOutputStream());
String str=dis.readLine();
out.println("Reply from"+InetAddress.getLocalHost()+";Length"+str.length());
c++;
}
s.close();}}
Output :
EXPERIMENT 5:
CREATE A SOCKET FOR HTTP FOR WEB PAGE UPLOAD AND DOWNLOAD.

OBJECTIVE: To write a java program for socket for HTTP for web page upload and
download .

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 CLASS

import javax.swing.*;
import java.net.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Client{
public static void main(String args[]) throws Exception{
Socket soc;
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();
}
soc.close();
}
}

//SERVER CLASS

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);
JLabel l = new JLabel();
l.setIcon(icon);
f.add(l);
f.pack();
f.setVisible(true);}}
Output

When you run the client code, following output screen would appear on client side.
EXPERIMENT 6:
WRITE A PROGRAM TO IMPLEMENT RPC (REMOTE PROCEDURE CALL)

OBJECTIVE: To write a C-program to implement Client – Server communication


using RPC.

DESCRIPTION: A remote procedure call (RPC) is an inter-process communication


that allows a computer program to cause a subroutine or procedure to execute in
another address space (commonly on another computer on a shared network)
without the programmer explicitly coding the details for this remote interaction.
(i) In RPC, the sender makes a request in the form of a procedure, function, or
method call. RPC translates these calls into requests sent over the network to the
intended destination.
(ii) The RPC recipient then processes the request based on the procedure name and
argument list, sending a response to the sender when complete.
(iii) The process is initiated by the client, which sends a request message to a known
remote server to execute a specified procedure with supplied parameters.
(iv) The remote server sends a response to the client, and the application continues
its process.
(v) While the server is processing the call, the client is blocked, it waits until the
server has finished processing before resuming execution.

ALGORITHM

Server:
Step 1: Start the program
Step 2: Create a socket with address family AF_INET type
SOCK_STREAM and default protocol.
Step 3: Initialize a socket and set its attributes.
Step 4: Bind the server to the socket using bind function.
Step 5: wait for the client request, on request establish a connection
using accept function.
Step 6: Read the number from the client by using
read method Step 7: Display the no.
Step 8: add the digits of a given number.
Step 9: send the result to the client by using
write method Step 10: stop the program.

Client:
Step 1: start.
Step 2: create a socket with address family.
Step 3: Initialize the socket and set its attributes set the
required port no. Step 4: Type AF_INET socket with default
protocol.
Step 5: Connect to server using connect function to initiate
the request. Step 6: send a no to the server using write
method.
Step 7: receive the result using read
method. Step 8: stop

PROGRAM:
//Client.java
import java.io.*;
import java.net.*;
import java.util.*;
class Clientrpc
{public static void main(String args[])
{try
{BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
Socket clsct=new Socket("127.0.0.1",139);
DataInputStream din=new DataInputStream(clsct.getInputStream());
DataOutputStream dout=new DataOutputStream(clsct.getOutputStream());
System.out.println("Enter String");
String str=in.readLine();
dout.writeBytes(str+'\n');
clsct.close();}
catch (Exception e)
{System.out.println(e);}}}
//Server.java
import java.io.*;
import java.net.*;
import java.util.*;
class Serverrpc
{public static void main(String args[])
{try
{ServerSocket obj=new ServerSocket(139);
while(true)
{Socket obj1=obj.accept();
DataInputStream din=new DataInputStream(obj1.getInputStream());
DataOutputStream dout=new DataOutputStream(obj1.getOutputStream());
String str=din.readLine();
Process p=Runtime.getRuntime().exec(str);}}
catch(Exception e)
{
System.out.println(e);
}
}
}
OUTPUT

Server
Y:\networks\remote>java Serverrpc
Client
Y:\networks\remote>java Clientrpc
Enter String
calc

Result :
www.studentsfocus.
Thus the program was implementing to implement RPC (remote procedure call)

RESULT:
Thus the Java-Program to implement Client - Server Communication using
RPC was executed and output verified using various samples.
EXPERIMENT 7:
IMPLEMENTATION OF SUBNETTING.

OBJECTIVE:Write a program to implement subnetting and find the subnet masks.

Algorithm :

Step1: Get the input from the user by using scanner method.
Step 2: Read the input by using nextLine() and store it.
Step 3: Split the string based on string by using split(“\\”)
Step4 : Convert it into binary.
Step 5: calculating the network mask by using math and logarithmic
Step 6: get the first address by ANDding the last n bits with 0.
Step7 : get the last address by ANDding the last n bits with 1.

Program

import java.util.Scanner;
class Subnet{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.print(“Enter the ip address: “);
String ip = sc.nextLine();
String split_ip[] = ip.split(“\\.”); //SPlit the string after every .
String split_bip[] = new String[4]; //split binary ip
String bip = “”;
for(int i=0;i<4;i++){
split_bip[i] = appendZeros(Integer.toBinaryString(Integer.parseInt(split_ip[i]))); // “18”
=> 18 => 10010 => 00010010
bip += split_bip[i];
}
System.out.println(“IP in binary is “+bip);
System.out.print(“Enter the number of addresses: “);
int n = sc.nextInt();

//Calculation of mask
int bits = (int)Math.ceil(Math.log(n)/Math.log(2)); /*eg if address = 120, log 120/log 2
gives log to the base 2 => 6.9068, ceil gives us upper integer */
System.out.println(“Number of bits required for address = “+bits);
int mask = 32-bits;
System.out.println(“The bits for subnet mask is = “+mask);

//Calculation of first address and last address


int fbip[] = new int[32];
for(int i=0; i<32;i++) fbip[i] = (int)bip.charAt(i)-48; //convert cahracter 0,1 to integer
0,1
for(int i=31;i>31-bits;i–)//Get first address by ANDing last n bits with 0
fbip[i] &= 0;
String fip[] = {“”,””,””,””};
for(int i=0;i<32;i++)
fip[i/8] = new String(fip[i/8]+fbip[i]);
System.out.print(“First address is = “);
for(int i=0;i<4;i++){
System.out.print(Integer.parseInt(fip[i],2));
if(i!=3) System.out.print(“.”);
}
System.out.println();

int lbip[] = new int[32];


for(int i=0; i<32;i++) lbip[i] = (int)bip.charAt(i)-48; //convert cahracter 0,1 to integer
0,1
for(int i=31;i>31-bits;i–)//Get last address by ORing last n bits with 1
lbip[i] |= 1;
String lip[] = {“”,””,””,””};
for(int i=0;i<32;i++)
lip[i/8] = new String(lip[i/8]+lbip[i]);
System.out.print(“Last address is = “);
for(int i=0;i<4;i++){
System.out.print(Integer.parseInt(lip[i],2));
if(i!=3) System.out.print(“.”);
}
System.out.println();
}
static String appendZeros(String s){
String temp = new String(“00000000”);
return temp.substring(s.length())+ s;
}
}
Output:

Enter the ip address: 100.110.150.10


IP in binary is 01100100011011101001011000001010
Enter the number of addresses: 7
Number of bits required for address = 3
The bits for subnet mask is = 29
First address is = 100.110.150.8
Last address is = 100.110.150.15
EXPERIMENT 8:
APPLICATIONS USING TCP SOCKETS LIKE,
(A) ECHO CLIENT AND ECHO SERVER
(B) CHAT
(C) FILE TRANSFER

a. Echo client and echo server

OBJECTIVE
To write a java program for applications using TCP Sockets Links

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

Program :
//echo client.java
import java.io.*;
import java.net.*;
import java.util.*;
public class echoclient
{
public static void main(String args[])throws Exception
{
Socket c=null;
DataInputStream usr_inp=null;
DataInputStream din=new DataInputStream(System.in);
DataOutputStream dout=null;
try
{
c=new Socket("127.0.0.1",5678);
usr_inp=new DataInputStream(c.getInputStream());
dout=new DataOutputStream(c.getOutputStream());
}
catch(IOException e)
{
}
if(c!=null || usr_inp!=null || dout!=null)
{
String unip;
while((unip=din.readLine())!=null)
{
dout.writeBytes(""+unip);
dout.writeBytes("\n");
System.out.println("\n the echoed message");
System.out.println(usr_inp.readLine());
System.out.println("\n enter your message");
}
System.exit(0);
}
din.close();
usr_inp.close();
c.close();
}
}

//echoserver.java
import java.io.*;
import java.net.*;
public class echoserver
{
public static void main(String args[])throws Exception
{
ServerSocket m=null;
Socket c=null;
DataInputStream usr_inp=null;
DataInputStream din=new DataInputStream(System.in);
DataOutputStream dout=null;
try
{
m=new ServerSocket(5678);
c=m.accept();
usr_inp=new DataInputStream(c.getInputStream());
dout=new DataOutputStream(c.getOutputStream());
}
catch(IOException e)
{}
if(c!=null || usr_inp!=null)
{
String unip;
while(true)
{
System.out.println("\nMessage from Client...");
String m1=(usr_inp.readLine());
System.out.println(m1);
dout.writeBytes(""+m1);
dout.writeBytes("\n");
}
}
dout.close();
usr_inp.close();
c.close();
}
}

Output :
Refer to Experiment 17.

b. Chat

Algorithm:

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

Client
Step1: Start the program and create a client socket that connects to the required
host and port.
Step2: Use input streams read message given by server and print it.
Step3: Use input streams; get the message from user to be given to the server.
Step4: Use output streams to write message to the server.
Step5: Stop the program.

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

OUTPUT:
Refer to Experiment 17.

c. File Transfer

Algorithm:

Server
Step1: Import java packages and create class file server.
Step2: Create a new server socket and bind it to the port.
Step3: Accept the client connection
Step4: Get the file name and stored into the BufferedReader.
Step5: Create a new object class file and realine.
Step6: If file is exists then FileReader read the content until EOF is reached.
Step7: Stop the program.
Client
Step1: Import java packages and create class file server.
Step2: Create a new server socket and bind it to the port.
Step3: Now connection is established.
Step4: The object of a BufferReader class is used for storing data content which has
been retrieved from socket object.
Step5: The content of file is displayed in the client window and the connection is closed.
Step6: Stop the program.
Program
//File Client
import java.io.*;
import java.net.*;
import java.util.*;
class Clientfile
{ public static void main(String args[])
{
try
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
Socket clsct=new Socket("127.0.0.1",139);
DataInputStream din=new DataInputStream(clsct.getInputStream());
DataOutputStream dout=new DataOutputStream(clsct.getOutputStream());
System.out.println("Enter the file name:");
String str=in.readLine();
dout.writeBytes(str+'\n');
System.out.println("Enter the new file name:");
String str2=in.readLine();
String str1,ss;
FileWriter f=new FileWriter(str2);
char buffer[];
while(true)
{ str1=din.readLine();
if(str1.equals("-1")) break;
System.out.println(str1);
buffer=new char[str1.length()];
str1.getChars(0,str1.length(),buffer,0);
f.write(buffer);}
f.close();
clsct.close();}
catch (Exception e)
{System.out.println(e);}}}
Server
import java.io.*;
import java.net.*;
import java.util.*;
class Serverfile
{ public static void main(String args[])
{Try
{ServerSocket obj=new ServerSocket(139);
while(true)
{Socket obj1=obj.accept();
DataInputStream din=new DataInputStream(obj1.getInputStream());
DataOutputStream dout=new DataOutputStream(obj1.getOutputStream());
String str=din.readLine();
FileReader f=new FileReader(str);
BufferedReader b=new BufferedReader(f);
String s;
while((s=b.readLine())!=null)
{ System.out.println(s);
dout.writeBytes(s+'\n');
}
f.close();
dout.writeBytes("-1\n");
}}
catch(Exception e)
{ System.out.println(e);}
}
Output:
File content
Computer networks
jhfcgsauf
jbsdava
jbvuesagv

client end:
Enter the file name:sample.txt

Server response:
Computer networks
jhfcgsauf
jbsdava
jbvuesagv
client end:
Enter the new file name: net.txt
Computer networks
jhfcgsauf
jbsdava
jbvuesagv
Destination file
Computer networks
jhfcgsauf
jbsdava
jbvuesagv
EXPERIMENT 9:
APPLICATIONS USING TCP AND UDP SOCKETS LIKE ,
A. DNS
B. SNMP
C. FILE TRANSFER

a. DNS

OBJECTIVE
To write a java program for DNS application program

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

Program

// UDP DNS Server

Udpdnsserver
java import java.io.*;
import java.net.*;
public class udpdnsserver
{
private static int indexOf(String[] array, String str)
{
str = str.trim();
for (int i=0; i < array.length; i++)
{
if (array[i].equals(str)) return i;
}
return -1;
}
public static void main(String arg[])throws IOException
{
String[] hosts = {"yahoo.com", "gmail.com","cricinfo.com", "facebook.com"};
String[] ip = {"68.180.206.184", "209.85.148.19","80.168.92.140", "69.63.189.16"};
System.out.println("Press Ctrl + C to Quit");
while (true)
{
DatagramSocket serversocket=new DatagramSocket(1362);
byte[] senddata = new byte[1021];
byte[] receivedata = new byte[1021];
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();
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();
}
}
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
b. SNMP

OBJECTIVE
To write a java program for SNMP application program

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

Program
import java.io.IOException;
import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.Target;
import org.snmp4j.TransportMapping;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.Address;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;
public class SNMPManager {
Snmp snmp = null;
String address = null;
* Constructor
* @param
add
*/
public SNMPManager(String add)
{
address = add;
public static void main(String[] args) throws IOException {
/**
* Port 161 is used for Read and Other operations
* Port 162 is used for the trap generation
*/
SNMPManager client = new SNMPManager("udp:127.0.0.1/161");
client.start()
public String getAsString(OID oid) throws IOException {
ResponseEvent event = get(new OID[] { oid });
return event.getResponse().get(0).getVariable().toString();
}
public ResponseEvent get(OID oids[]) throws IOException {
PDU pdu = new PDU();
for (OID oid : oids) {
pdu.add(new VariableBinding(oid));
}
pdu.setType(PDU.GET);
ResponseEvent event = snmp.send(pdu, getTarget(), null);
if(event != null) {return event;}
throw new RuntimeException("GET timed out");
}
private Target getTarget() {
Address targetAddress = GenericAddress.parse(address);
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString("public"));
target.setAddress(targetAddress);
target.setRetries(2);
target.setTimeout(1500);
target.setVersion(SnmpConstants.version2c);
return target;
}
}
OUT PUT
Hardware: x86 Family 6 Model 23 Stepping 10 AT/AT COMPATIBLE – Software:
Windows
2000 Version 5.1 (Build 2600 Multiprocessor Free)

b. File Transfer

OBJECTIVE
To write a java program for FTP using TCP and UDP Sockets Liks

Program
File Client
import java.io.*;
import java.net.*;
import java.util.*;
class Clientfile
{ public static void main(String args[])
{
Try
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
Socket clsct=new Socket("127.0.0.1",139);
DataInputStream din=new DataInputStream(clsct.getInputStream());
DataOutputStream dout=new DataOutputStream(clsct.getOutputStream());
System.out.println("Enter the file name:");
String str2=in.readLine();
String str1,ss;
FileWriter f=new FileWriter(str2);
char buffer[];
while(true)
{ str1=din.readLine();
if(str1.equals("-1")) break;
System.out.println(str1);
buffer=new char[str1.length()];
str1.getChars(0,str1.length(),buffer,0);
f.write(buffer);
}
f.close();
clsct.close();
}
catch (Exception e)
{
System.out.println(e);}}}

Server
import java.io.*;
import java.net.*;
import java.util.*;
class Serverfile
{ public static void main(String args[])
{
Try
{
ServerSocket obj=new ServerSocket(139);
while(true)
{
Socket obj1=obj.accept();
DataInputStream din=new DataInputStream(obj1.getInputStream());
DataOutputStream dout=new DataOutputStream(obj1.getOutputStream());
String str=din.readLine();
FileReader f=new FileReader(str);
BufferedReader b=new BufferedReader(f);
String s;
while((s=b.readLine())!=null)
{ System.out.println(s);
dout.writeBytes(s+'\n');
}
Output
File content
Computer networks
jhfcgsauf
jbsdava
jbvuesagv
client
Enter the file name:
sample.txt
server
Computer networks
jhfcgsauf
jbsdava
jbvuesagv
client
Enter the new file name:
net.txt
Computer networks
jhfcgsauf
jbsdava
jbvuesagv
Destination file
Computer networks
jhfcgsauf
jbsdava
jbvuesagv
EXPERIMENT 10:
STUDY OF NETWORK SIMULATOR (NS) AND SIMULATION OF CONGESTION
CONTROL ALGORITHMS USING NS.

OBJECTIVE: To Study of Network simulator (NS) and Simulation of Congestion


Control Algorithms using NS.

NET WORK SIMULATOR (NS2)


NS overview
 Ns programming: A Quick start
 Case study I: A simple Wireless network
 Case study II: Create a new agent in Ns
 Ns Status
 Periodical release (ns-2.26, Feb 2003)
 Platform support
 FreeBSD, Linux, Solaris, Windows and Mac

NS Functionalities
Routing, Transportation, Traffic sources,Queuing disciplines, QoS

Wireless
Ad hoc routing, mobile IP, sensor-MAC Tracing, visualization and various utilitie NS
(Network Simulators) Most of the commercial simulators are GUI driven, while some
Network simulators are CLI driven. The network model / configuration describes the
state of the network (nodes,routers, switches, links) and the events (data
transmissions, packet error etc.). An important output of simulations are the trace
files. Trace files log every packet, every event that occurred in the simulation and are
used for analysis. Network simulators can also provide other tools to facilitate visual
analysis of trends and potential trouble spots.
Most network simulators use discrete event simulation, in which a list of pending
"events" is stored, and those events are processed in order, with some events
triggering future events—such as the event of the arrival of a packet at one node
triggering the event of the arrival
of that packet at a downstream node.
Simulation of networks is a very complex task. For example, if congestion is high,
thenestimation of the average occupancy is challenging because of high variance.
To estimate the likelihood of a buffer overflow in a network, the time required for an
accurate answer can be extremely large. Specialized techniques such as "control
variates" and "importance sampling" have been developed to speed simulation.

Examples of network simulators


There are many both free/open-source and proprietary network simulators.
Examples of
notable network simulation software are, ordered after how often they are mentioned
in research papers:
1. NS (open source)
2. OPNET (proprietary software)
3. NetSim (proprietary software)

Uses of network simulators


Network simulators serve a variety of needs. Compared to the cost and time
involved in setting up an entire test bed containing multiple networked computers,
routers and data links, network simulators are relatively fast and inexpensive. They
allow engineers, researchers to test scenarios that might be particularly difficult or
expensive to emulate using real hardware - for instance simulating a scenario with
several nodes or experimenting with a new protocol in the network.
Network simulators are particularly useful in allowing researchers to test new
networking
protocols or changes to existing protocols in a controlled and reproducible
environment. A
typical network simulator encompasses a wide range of networking technologies
and can help
the users to build complex networks from basic building blocks such as a variety of
nodes and links. With the help of simulators, one can design hierarchical networks
using various types of nodes like computers, hubs, bridges, routers, switches, links,
mobile units etc.
Various types of Wide Area Network (WAN) technologies like TCP, ATM, IP etc. and
Local
Area Network (LAN) technologies like Ethernet, token rings etc., can all be simulated
with a
typical simulator and the user can test, analyze various standard results apart from
devising some novel protocol or strategy for routing etc. Network simulators are also
widely used to simulate battlefield networks in Network-centric warfare. There are a
wide variety of network simulators, ranging from the very simple to the very complex.
Minimally, a network simulator must enable a user to represent a network topology,
specifying the nodes on the network, the links between those nodes and the traffic
between the nodes. More complicated systems may allow the user to specify
everything about the protocols used to handle traffic in a network. Graphical
applications allow users to easily visualize the workings of their simulated
environment. Text-based applications may provide a less intuitive interface, but may
permit more advanced forms of customization.

Packet loss
Occurs when one or more packets of data travelling across a computer networkfail
to reach their destination. Packet loss is distinguished as one of the three main error
types encountered in digital communications; the other two being bit errorand
spurious packets caused due to noise.
Packets can be lost in a network because they may be dropped when a queue in the
network node overflows. The amount of packet loss during the steady state is
another important property of a congestion control scheme. The larger the value of
packet loss, the more difficult it is for transportlayer protocols to maintain high
bandwidths, the sensitivity to loss of individual packets, as well as to frequency and
patterns of loss among longer packet sequences is strongly dependent on the
application itself.

Throughput
This is the main performance measure characteristic, and most widely used.
Incommunicationnetworks, such asEthernetorpacket radio, throughputor network
throughputis the average rate of successfulmessage delivery over a communication
channel. The throughput is usually measured inbitsper second (bit/s orbps),
andsometimes indata packetsper second or data packets pertime slotThis measure
how soon the receiver is able to get a certain amount of data send by the sender. It is
determined as the ratio of the total data received to the end to end delay. Throughput
is an important factor which directly impacts the network performance.

Delay
Delay is the time elapsed while a packet travels from one point e.g., source premise
or network ingress to destination premise or network degrees. The larger the valueof
delay, the more difficult it is for transport layer protocols to maintain highbandwidths.
We will calculate end to end delay.

Queue Length
A queuing system in networks can be described as packets arriving for service,
waiting for
service if it is not immediate, and if having waited for service, leaving thesystem after
being
served. Thus queue length is very important characteristic to determine that how
well the active queue management of the congestion control algorithm has been
working.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy