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

Cse CN

The document describes algorithms for implementing various network programming concepts using TCP sockets in Java, including an echo server, file transfer, remote command execution, and a chat application. For each concept, it provides the client and server code with comments explaining the key steps. It also includes sample outputs for verification. The goals are to write programs to transfer data between clients and servers, enable remote execution of commands, and allow real-time messaging between connected devices.

Uploaded by

Mani
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)
59 views

Cse CN

The document describes algorithms for implementing various network programming concepts using TCP sockets in Java, including an echo server, file transfer, remote command execution, and a chat application. For each concept, it provides the client and server code with comments explaining the key steps. It also includes sample outputs for verification. The goals are to write programs to transfer data between clients and servers, enable remote execution of commands, and allow real-time messaging between connected devices.

Uploaded by

Mani
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/ 60

Ex.

No:1
Date: IMPLEMENTATION OF ECHO SERVER

AIM:
To Write a Network Socket program for implementing the echo operation.

ALGORITHM:
Step 1: Client sends the request to server; server runs the request and creates the
connection between the client and the server
Step 2: Message send by the client and server is stored in input stream and from stream
it is displayed on the server.
Step 3: The same message is sent back from server to client and is displayed on client.
Step 4: Stop the program.
SERVER PROGRAM:
import java.io.*;
import java.net.*;
import java.lang.String.*;
public class Secho
{
public static void main(String args[]) throws Exception
{
ServerSocket ss =new ServerSocket(123);
Socket s=ss.accept();
DataInputStream in= new DataInputStream(s.getInputStream());
DataOutputStream out=new DataOutputStream(s.getOutputStream());
String str;
System.out.println("\nSERVER SIDE!...");
while(true)
{
str=in.readLine();
out.writeBytes(str+"\n");
System.out.println("Msg from Client");
System.out.println(str+"\n");
}
}
}

CLIENT PROGRAM:
import java.io.*;
import java.net.*;
import java.lang.String.*;
public class Cecho
{
public static void main(String args[]) throws Exception
{
DataInputStream in=new DataInputStream (System.in);
Socket s=new Socket("LocalHost",123);
DataInputStream inecho=new DataInputStream(s.getInputStream());
DataOutputStream out=new DataOutputStream(s.getOutputStream());
String str;
System.out.println("\nCLIENT SIDE!...\nType EXIT TO QUIT\nEnter Client
Msg");
while((str=in.readLine())!=null)
{
out.writeBytes(str+"\n");
if(str.equals("exit"))
{
out.writeBytes("\nClient Terminated");
break;
}
else
{
System.out.println("\nEcho From Server");
System.out.print(str+"\n");
System.out.println("\nCLIENT SIDE!...\nEnter Client Msg");
}
}
}
}
OUTPUT:
SERVER OUTPUT:

CLIENT OUTPUT:

RESULT:
Thus the program was executed and output is verified successfully.
Ex.No:2
Date: FILE TRANSFER

AIM:
To write a program to transfer the message in Flag through the socket using network
program.

ALGORITHM:
Step 1: In order to transfer the data create the socket and client and server
Step 2: At Client side along with port number to be used specifying IP address of
server
Step 3: Data provided by client are passed to the server through class output stream.
Step 4: Server receiver the data through its input stream class until line break.
Step 5: After transfer of data the connected and stream that are opened or closed.
Step 6: Connection remains infact as long as these is data transmission.
Step 7: Stop the program.
PROGRAM:
SERVER PROGRAM:
import java.io.*;
import java.net.*;
class Tcpserver
{public static void main(String args[])
{ try
{
ServerSocket s1=new ServerSocket(5000);
Socket c=null;
String aa="";
System.out.println("U will get the data");
c=s1.accept();
DataInputStream in=new DataInputStream(c.getInputStream());
DataOutputStream out=new DataOutputStream(c.getOutputStream());
DataInputStream user=new DataInputStream(System.in);
System.out.println("File requested:");
aa=in.readUTF();
String s2="";
try
{
FileReader f=new FileReader(aa);
BufferedReader b=new BufferedReader(f);
String d;
while((d=b.readLine())!=null){
s2=s2+d+"\n";}
System.out.println(s2);
out.writeUTF(s2);
}
catch(Exception e1)
{
System.out.println(e1);
}
out.close();
user.close();
in.close();
c.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
CLIENT PROGRAM:
import java.io.*;
import java.net.*;
class tcpclient
{
public static void main(String args[])
{
try
{
Socket c=new Socket("localhost",5000);
String a="";
String b="";
String s="";
DataInputStream in=new DataInputStream(c.getInputStream());
DataOutputStream out=new DataOutputStream(c.getOutputStream());
DataInputStream user=new DataInputStream(System.in);
System.out.println("enter the file name:");
b=user.readLine();
a=b;
out.writeUTF(a);
s=in.readUTF();
System.out.println(s);
out.close();
user.close();
in.close();
c.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
OUTPUT:
SERVER OUTPUT:

CLIENT OUTPUT:

RESULT:
Thus the program was executed and output is verified successfully.
Ex.No:3
Date: IMPLEMENTATION OF REMOTE COMMAND EXECUTION

AIM:
To write a network program for executing the command remotely in a Remote
Machine.

ALGORITHM:
Step 1: Start the program
Step 2: Create the interface to define action, provide the input command through the
client in remotely machine
Step 2: Create remote object for communication
Step 4: Give the URL of remote machine
Step 5: Execute the process in server machine
Step 6: perform the operation
Step 7: Return the result
Step 8: Stop the program.
SERVER PROGRAM:
import java.io.*;
import java.net.*;
import java.lang.String.*;
public class Rceserver{
public static void main(String args[]) throws Exception{
ServerSocket ss =new ServerSocket(111);
Socket s=ss.accept();
DataInputStream in= new DataInputStream(s.getInputStream());
String str;
str=in.readLine();
Runtime r=Runtime.getRuntime();
Process p=null;
p=r.exec(str);
System.out.println(str+" has been executed successfully");}}

CLIENT PROGRAM:
import java.io.*;
import java.net.*;
import java.lang.String.*;
public class Rceclient{
public static void main(String args[]) throws Exception{
Socket s=new Socket("LocalHost",111);
DataInputStream sin=new DataInputStream(System.in);
DataOutputStream out=new DataOutputStream(s.getOutputStream());
String str;
System.out.println("\nEnter Command to be excuted");
str=sin.readLine();
out.writeBytes(str+"\n");
System.out.println(str+" has been executed on the server");
}}
OUTPUT:
CLIENT OUTPUT:

SERVER OUTPUT:
RESULT:
Thus the program was executed and output is verified successfully.
Ex.No:4
Date: CHAT APPLICATION

AIM:
To write a network program for implementing chat using TCP socket.

ALGORITHM:
Step 1: Client sends the request to server
Step 2: Server run the request and the connection with the client that has requested the
server.
Step 3: The client send the message to server.
Step 4: The server process it and it is displayed (ie)replier by sending the message to
client also displayed.
Step 5: Stop the program.
SERVER PROGRAM:
import java.io.*;
import java.net.*;
public class chatserver
{
public static void main(String args[])throws Exception
{
DataInputStream din=null;
DataOutputStream dout=null;
Socket c=null;
ServerSocket m=null;
DataInputStream stdin=new DataInputStream(System.in);
try
{
m=new ServerSocket(68);
c=m.accept();
din=new DataInputStream(c.getInputStream());
dout=new DataOutputStream(c.getOutputStream());
}
catch(Exception e)
{
}
while(c!=null)
{
String m2;
System.out.println("Server");
while(true){
String m1=din.readLine();
System.out.println("Message from client.."+m1);
System.out.println("\n\n Enter the message...");
m2=stdin.readLine();
dout.writeBytes(""+m2);
dout.writeBytes("\n");
}
}
din.close();
dout.close();
c.close();
m.close();
}
}

CLIENT PROGRAM:
import java.io.*;
import java.net.*;
public class chatclient{
public static void main(String args[])throws Exception{
Socket c=null;
DataInputStream uin=null;
DataInputStream din=null;
DataOutputStream dout=null;
try
{
c=new Socket("localhost",68);
uin=new DataInputStream(System.in);
din=new DataInputStream(c.getInputStream());
dout=new DataOutputStream(c.getOutputStream());
}
catch(Exception e){
}
if(c!=null){
String inp;
System.out.println("Enter the message:");
while((inp=uin.readLine())!=null){
dout.writeBytes(""+inp);
dout.writeBytes("\n");
System.out.println("Echoed message from server.."+din.readLine());
System.out.println("Enter ur message:");
}
}
din.close();
dout.close();
c.close();
}
}
OUTPUT:
CLIENT OUTPUT:

SERVER OUTPUT:

RESULT:
Thus the program was executed and output is verified successfully.
Ex.No:5
Date: CONCURRENT SERVER

AIM:
To write a network program to send the data from server to client using concurrent
server

ALGORITHM:
Step 1: Start the program.
Step 2: In the server side create TCP socket object
Step 3: In the client side create the TCP socket object
Step 4: Read the message and send it to the client specifying the port number of the
client.
Step 5: In the client send acknowledgment to server
Step 6: Stop the program.
CLIENT PROGRAM:
import java.io.*;
import java.net.*;
class siclient{
public static DatagramSocket ds,as;
public static byte buffer[]=new byte[1024];
public static byte ackbuffer[]=new byte[1024];
public static int clientport=571,ackport=540,ackserverport=449;
public static void main(String args[]) throws Exception{
System.out.println("client side");
ackbuffer[0]=(byte)'a';
ds=new DatagramSocket(clientport);
as=new DatagramSocket(ackserverport);
while(true)
{
DatagramPacket p=new DatagramPacket(buffer,buffer.length);
ds.receive(p);
as.send(new DatagramPacket(ackbuffer,1,InetAddress.getByName("sys163"),ackport));
String psx=new String(p.getData(),0,p.getLength());
System.out.println(psx);
System.out.println("Message received");
}
}
}

SERVER PROGRAM:
import java.io.*;
import java.net.*;
class siserver{
public static DatagramSocket ds,as;
public static int clientport=571,serverport=540,ackport=449;
public static byte ackbufffer[]=new byte[1024];
public static void main(String args[]) throws Exception
{
System.out.println("\n\n synchronization(server side)");
System.out.println("\t The message from server to client is:");
byte buffer[]=new byte[1024];
int i=0;
ds=new DatagramSocket(serverport);
BufferedReader dis=new BufferedReader(new InputStreamReader(System.in));
as=new DatagramSocket(ackport);
while(true)
{
int c=System.in.read();
if(c=='\n')
{
ds.send(new DatagramPacket(buffer,i,InetAddress.getByName("sys163"),clientport));
DatagramPacket ack1=new DatagramPacket(buffer,buffer.length);
as.receive(ack1);
System.out.println("\n\t acknowlw=edgement received");
System.out.println("\n\t press ctrl+c to enter prompt");
i=0;
}
else{
i=i+1;
buffer[i]=(byte)c;
}}
}
}
Server Output:

RESULT:
Thus the program was executed and output is verified successfully.
Ex.No:6
Date: DNS CLIENT AND SERVER

Aim:
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


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]; 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();
}
}
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:
Thus the program was executed and output is verified successfully.
Ex.No:7 SNMP
Date:
Aim
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();
/**
* OID - .1.3.6.1.2.1.1.1.0 => SysDec
* OID - .1.3.6.1.2.1.1.5.0 => SysName
* => MIB explorer will be usefull here, as discussed in previous article
*/
String sysDescr = client.getAsString(new OID(".1.3.6.1.2.1.1.1.0"));
System.out.println(sysDescr);
}

/**
* get any answers because the communication is asynchronous
* and the listen() method listens for answers.
* @throws IOException
*/
private void start() throws IOException {
TransportMapping transport = new DefaultUdpTransportMapping();
snmp = new
Snmp(transport);
// Do not forget this line!
transport.listen();
}

/**
* Method which takes a single OID and returns the response from the agent as a String.
* @param oid
* @return
* @throws IOException
*/
public String getAsString(OID oid) throws IOException {
ResponseEvent event = get(new OID[] {oids});
return event.getResponse().get(0).getVariable().toString();
}
/**
* This method is capable of handling multiple OIDs
* @param oids
* @return
* @throws IOException
*/
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");
}
/**
* This method returns a Target, which contains information about
* where the data should be fetched and how.
* @return
*/
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)

RESULT
Thus the SNMP program was displayed
Ex.No:8
Date: PING ALGORITHM

AIM:
To write a network program to implement PING.

ALGORITHM:
Step 1: Start the program
Step 2: First run the server program
Step 3: Then run the client program
Step 4: Get the number of string
Step 5: Then get the message for the server from client
Step 6: Then execute the program
Step 7: Stop the program
SERVER PROGRAM:
import java.io.*;
import java.net.*;
import java.util.*;
import java.text.*;
class Pserver
{
public static void main(String args[]) throws Exception
{
ServerSocket ss = new ServerSocket(555);
Socket s = ss.accept();
int c = 0;
while (c < 4)
{
DataInputStream in = new DataInputStream(s.getInputStream());
PrintStream out = new PrintStream(s.getOutputStream());
String str = in.readLine();
out.println("Reply from " + InetAddress.getLocalHost() + "; Length "
+ str.length());
c++;
}
s.close();
}
}

CLIENT PROGRAM:
import java.io.*;
import java.net.*;
import java.util.Calendar;
public class Pclient{
public static void main(String args[]) throws Exception
{
String str;
int c = 0;
long t1, t2;
Socket s = new Socket("localhost", 555);
DataInputStream in = new DataInputStream(s.getInputStream());
PrintStream out = new PrintStream(s.getOutputStream());
while (c < 4) {
t1 = System.currentTimeMillis();
str = "Welcome to our College";
out.println(str);
System.out.print(in.readLine());
t2 = System.currentTimeMillis();
System.out.println("; TTL = " + (t2 - t1) + " ms");
c++;
}
s.close();
}
}
Output:
Server Output:

ClientOutput:

RESULT:
Thus the program was executed and output is verified successfully.\
Ex.No:9
Date: REMOTE PROCEDURE CALL

AIM:
To write a network program to call the Remote running process.

ALGORITHM:
Step 1: Start the program
Step 2: Implement the operation to be in the procedure.
Step 3: In server side. register list of performance object in the RMI registry
Step 4: By starting the RMI registry we can run our server program to keep the
program run always.
Step 5: If the client want to involve to the procedure by means that by biding the
registered object in the RMI registry if(client) call the procedure and produce the
result..
Step 6: Stop the program.
Program 1 for RPC (Interface):

import java.rmi.*;
public interface greater extends Remote
{
public String getresult(int first,int second)throws RemoteException;
}

RPC Program for client:


import java.io.*;
import java.rmi.*;
public class great
{
public static void main(String args[]) throws IOException
{
String result;
int n=0,n1=0;
try
{
greater f=(greater)Naming.lookup("greaterser");
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("\n\n\t Rpc program for clientside");
System.out.println("\n\n\t ******************************");
System.out.println("\n\t Enter the two numbers");
System.out.println("\n\t the First number is :");
n=Integer.parseInt(br.readLine());
System.out.println("\n\t the Second number is:");
n1=Integer.parseInt(br.readLine());
}
catch(IOException e)
{
}
result=f.getresult(n,n1);
if(result.equals("Equal"))
System.out.println("\n\n\t Both nos are equal");
else
System.out.println("\n\n\t The greater no is"+result);
}
catch(Exception e)
{
System.out.println("Exception from client side:"+e);
}
}
}

RPC Program for server:

import java.io.*;
import java.rmi.*;
import java.rmi.server.*;
import java.util.*;
public class greaterser extends UnicastRemoteObject implements greater
{
public greaterser()throws RemoteException{}
public String getresult(int first,int second)throws RemoteException
{
if(first<second)
return(Integer.toString(second));
else
{
if(second<first)
return(Integer.toString(first));
else
return("EQUAL");
}
}
public static void main(String args[])
{
try
{
greaterser f=new greaterser();
Naming.rebind("greaterser",f);
System.out.println("\n\n\t Server is ready");
}
catch(Exception e)
{
System.out.println("error from ss");
}
}
}
OUTPUT:
Server output:

Client output:

RESULT:
Thus the program was executed and output is verified successfully.
Ex.No:10
Date: PERFORMANCE COMPARISON OF MAC PROTOCOLS

AIM:
To write a program to perform comparison of MAC protocols

ALGORITHM:
Step 1: Start the program
Step 2: First run the server program.
Step 3: Then run the client program
Step 4: Enter the Host Address
Step 5: Get the IP Address.
Step 6: Execute the program.
Step 7: Stop the program

CLIENT PROGRAM:

import java.io.*;
import java.net.*;
class clientmac
{
public static void main(String args[]) throws Exception{
String mac[]={"00-Do-09-Do-22-48"};
String ip[]={"192.168.0.42"};
DatagramSocket ds=new DatagramSocket(1234);
DatagramPacket udp=new
DatagramPacket(buf,buf.length,InetAddress.getLocalHost(),1235);
ds.receive(udp);
String s=new String(udp.getData(),0,udp.getLength());
int i=0;
while(i<=2){
if(ip[i].compareTo(s)==0){
buf=mac[i].getBytes();
udp=new
DatagramPacket(buf,buf.length,InetAddress.getByName("127.0.0.255"),1235);
ds.send(udp);
}
i++;
}
}}

SERVER PROGRAM:
import java.io.*;
import java.net.*;
class mac{
public static void main(String args[]) throws Exception{
DataInputStream dis=new DataInputStream(System.in);
byte buf[]=new byte[1028];
String s="192.168.0.42",s2="192.168.0.42";
buf=s.getBytes();
DatagramPacket udp=new
DatagramPacket(buf,buf.length,InetAddress.getByName("127.0.0.25"),(1235));
DatagramSocket ds=new DatagramSocket(1235);
ds.send(udp);
buf=new byte[1024];
udp=new DatagramPacket(buf,buf.length,InetAddress.getLocalHost(),1234);
ds.receive(udp);
s=new String(udp.getData(),0,udp.getLength());
System.out.println("The mac address of ip"+s2+"is"+s);
}
}
OUTPUT:
Server output:

Client output:

RESULT:
Thus the program was executed and output is verified successfully.
Ex.No:11 PERFORMANCE COMPARISON OF ROUTING PROTOCOLS
Date:

AIM:
To write a program to perform comparison of routing protocols

ALGORITHM:
Step 1: Start the program
Step 2: Enter the number of nodes and set the input value if there is an edge otherwise
put infinity (1000) values.
Step 3: Find the shortest path from the entire using Batment forte algorithm.
Step 4: Print the distance from source.
Step5: Print the shortest path (length) of given path
Step 6: Display the result
Step 7: Stop the program.
PROGRAM:
import java.io.*;
class router
{
public static void main(String args[]) throws Exception
{
int i,j,u,k,n,x,m,a;
n=0;
int dist[][]=new int[5][5];
int cost[][]=new int[5][5];
int res[][]=new int[8][8];
int result[][]=new int[8][8];
System.out.println("\n\t\t Shortest path");
System.out.println("\n\t\t Enter the no of nodes:");
InputStreamReader read=new InputStreamReader(System.in);
BufferedReader in=new BufferedReader(read);
try
{
n=Integer.parseInt(in.readLine());
}
catch(Exception e)
{
}
for(i=1;i<=n;i++)
{
cost[i][i]=0;
res[i][i]=1;
}
System.out.println("\n\t\t Input valuesfrom cost if there is an edge:");
System.out.println("\n\t\t Otherwise put Indefinitely(10000)values");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(i!=j)
{
System.out.println("\n\t\t cost of "+i+"&"+j+":");
try
{
cost[i][j]=Integer.parseInt(in.readLine());
}
catch(Exception e)
{
}
}
for(i=1;i<=n;i++)
{
if(cost[i][i]==0)
dist[i][i]=10000;
else
dist[1][i]=cost[i][i];
dist[i][1]=0;
}
for(k=2;k<n;k++)
{
for(u=2;u<=n;u++)
{
x=dist[k-1][u];
for(j=1;j<n;j++)
if(j!=u)
{
if(x>dist[k-1][j]+cost[j][u])
{
x=dist[k-1][j]+cost[j][u];
res[u][u]=j;
}
}
dist[k][u]=x;
}
}
m=n;i=1;
do
{
a=res[m][m];
result[i][i]=a;
i++;
m=a;
}
while(a!=1);
System.out.println("\n\t\t\t shortest path of given graph");
System.out.println("\n\t\t\t shortest path is");
for(j=1;j>=1;j--)
System.out.println(""+result[j][j]+"-->");
System.out.println(""+n);
}
}
OUTPUT:

RESULT:
Thus the program was executed and output is verified successfully.
Ex.No:12
Date: STUDY OF UDP/TCP PERFORMANCE

AIM:
To study the performance of the UDP/TCP protocols

The TCP Connection

TCP provides multiplexing, demultiplexing, and error detection (but not recovery) in exactly
the same manner as UDP. Nevertheless, TCP and UDP differ in many ways. The most
fundamental difference is that UDP is connectionless, while TCP is connection-oriented.
UDP is connectionless because it sends data without ever establishing a connection. TCP is
connection-oriented because before one application process can begin to send data to another,
the two processes must first "handshake" with each other -- that is, they must send some
preliminary segments to each other to establish the parameters of the ensuing data transfer.
As part of the TCP connection establishment, both sides of the connection will initialize
many TCP "state variables" (many of which will be discussed in this section and in Section
3.7) associated with the TCP connection.

The TCP "connection" is not an end-to-end TDM or FDM circuit as in a circuit-switched


network. Nor is it a virtual circuit (see Chapter 1), as the connection state resides entirely in
the two end systems. Because the TCP protocol runs only in the end systems and not in the
intermediate network elements (routers and bridges), the intermediate network elements do
not maintain TCP connection state. In fact, the intermediate routers are completely oblivious
to TCP connections; they see data grams, not connections.

A TCP connection provides for full duplex data transfer. That is, application-level data can be
transferred in both directions between two hosts - if there is a TCP connection
between process A on one host and process B on another host, then application-level data can
flow from A to B at the same time as application-level data flows from B to A. TCP
connection is also always point-to-point, i.e., between a single sender and a single receiver.
So called "multicasting" (see Section 4.8) -- the transfer of data from one sender to many
receivers in a single send operation -- is not possible with TCP. With TCP, two hosts are
company and three are a crowd!

Let us now take a look at how a TCP connection is established. Suppose a process running in
one host wants to initiate a connection with another process in another host. Recall that the
host that is initiating the connection is called the client host, while the other host is called the
server host. The client application process first informs the client TCP that it wants to
establish a connection to a process in the server. Recall from Section 2.6, a Java client
program does this by issuing the command:
Socket clientSocket = new Socket ("hostname", "port number");

The TCP in the client then proceeds to establish a TCP connection with the TCP in the server.
We will discuss in some detail the connection establishment procedure at the end of this
section. For now it suffices to know that the client first sends a special TCP segment; the
server responds with a second special TCP segment; and finally the client responds again
with a third special segment. The first two segments contain no "payload," i.e., no
application-layer data; the third of these segments may carry a payload. Because three
segments are sent between the two hosts, this connection establishment procedure is often
referred to as a three-way handshake.

Once a TCP connection is established, the two application processes can send data to each
other; because TCP is full-duplex they can send data at the same time. Let us consider the
sending of data from the client process to the server process. The client process passes a
stream of data through the socket (the door of the process), as described in Section 2.6. Once
the data passes through the door, the data is now in the hands of TCP running in the client. As
shown in the Figure 3.5-1, TCP directs this data to the connection's send buffer, which is one
of the buffers that is set aside during the initial three-way handshake. From time to time,
TCP will "grab" chunks of data from the send buffer. The maximum amount of data that can
be grabbed and placed in a segment is limited by the Maximum Segment Size (MSS). The
MSS depends on the TCP implementation (determined by the operating system) and can
often be configured; common values are 1,500 bytes, 536 bytes and 512 bytes. (These
segment sizes are often chosen in order to avoid IP fragmentation, which will be discussed in
the next chapter.) Note that the MSS is the maximum amount of application-level data in the
segment, not the maximum size of the TCP segment including headers. (This terminology is
confusing, but we have to live with it, as it is well entrenched.)

Figure 3.5-1: TCP send and receive buffers

TCP encapsulates each chunk of client data with TCP header, thereby forming TCP
segments. The segments are passed down to the network layer, where they are separately
encapsulated within network-layer IP data grams. The IP data grams are then sent into the
network. When TCP receives a segment at the other end, the segment's data is placed in the
TCP connection's receive buffer. The application reads the stream of data from this buffer.
Each side of the connection has its own send buffer and its own receive buffer. The send and
receive buffers for data flowing in one direction are shown in Figure 3.5-1.
We see from this discussion that a TCP connection consists of buffers, variables and a socket
connection to a process in one host, and another set of buffers, variables and a socket
connection to a process in another host. As mentioned earlier, no buffers or variables are
allocated to the connection in the network elements (routers, bridges and repeaters) between
the hosts.
Structure of a TCP segment

When a TCP application sends a data, it divides into number of TCP segments. These
segments include part of the data along with the header that defines various parameters used
in the TCP communication between the source and the destination. These TCP segments are
then encapsulated within the data portion of an IP datagram and sent on their way. If TCP are
sent inside IP datagram, and I just said that IP is unreliable.

How can TCP possibly be reliable?

The trick is that, unlike straight IP, TCP expects a response from its TCP computer on
receiving end. Think of this way: Imagine mailing a letter again!!, to someone and including
a Post-it Note on the letter that specifies your phone number and tells the recipient to call you
when she receives the letter. If you don't hear from her, you know she didn't get the letter. To
ensure reliable communication, TCP includes a "Post-it Note" in its header that does two
things:

 When the application requests that the data be sent a remote location, TCP
constructs an initial segment that attempts to set up the socket interface
between the two systems. No data is sent until TCP hears back from the
receiving system that the sockets are in place and that's ready to receive the
data.
 When the sockets are ready to go, TCP starts sending within its segments and
always asks receiving TCP to acknowledge that these data segments have
arrived. If no acknowledgement is received, the sending TCP retransmits the
segments.

Here is the exact format of TCP header.

Field Bits Description


Source Port 0 to 15 The source port number

Destination Port 16 to 31 The destination number

In the overall sequence of


Sequence Number bytes being sent, this field
32 to 63
specifies the position in this
sequence of the segment's
first data byte.

In the ACK control Bit is set,


this field contains the value
of the next sequence number
Acknowledgement 64 to 95 the sender of the segments is
expecting the receiver to
acknowledge.

The length of the TCP


segment header, in 32 bit
Data Offset 96 to 99 words.This tells the
receiving socket where the
data starts.

This field is reserved for


Reserved 100 to 105 future use!

Those codes specify various


aspects of the
communication.When set to
1, each bit controls a
particular code as listed
here:

106 URG: Urgent pointer


field significant.

107 ACK:Acknowledgment
Number field to be used.
Control Bits 106 to 111
108 PSH: Push Function.

109 RST: Reset the


connection.

110 SYN: Synchronize


sequence numbers.This bit is
set when the connection is
opened.

111 FIN: No more data form


sender, so close the
connection.
The number of data bytes
that the sender can currently
accept. This sliding window
Windows 112 to 127 lets the sender and the
receiver vary the number of
bytes sent and thus increase
efficiency.

This value lets the receiver


Checksum 128 to 143 determine the integrity of the
data.

If the URG control bit is set,


this field indicates the
Urgent Pointer 144 to 159 location in the data where
the urgent resides.

This variable-length field


specifies extra TCP options
Options 160 and over such as the maximum
segment size.

TCP Header Format

TCP segments are sent as internet datagrams. The Internet Protocol header carries several
information fields, including the source and destination host addresses [2]. A TCP header
follows the internet header, supplying information specific to the TCP protocol. This division
allows for the existence of host level protocols other than TCP.

TCP Header Format


Source Port: 16 bits

The source port number.

Destination Port: 16 bits

The destination port number.

Sequence Number: 32 bits

The sequence number of the first data octet in this segment (except When SYN is present).
If SYN is present the sequence number is the initial sequence number (ISN) and the first data
octet is ISN+1.

Acknowledgment Number: 32 bits

If the ACK control bit is set this field contains the value of the next sequence number the
sender of the segment is expecting to receive. Once a connection is established this is always
sent.

Data Offset: 4 bits

The number of 32 bit words in the TCP Header. This indicates where the data begins. The
TCP header (even one including options) is an integral number of 32 bits long.

Reserved: 6 bits
Reserved for future use. Must be zero.

Control Bits: 6 bits (from left to right):

URG: Urgent Pointer field significant

ACK: Acknowledgment field significant

PSH: Push Function

RST: Reset the connection

SYN: Synchronize sequence numbers

FIN: No more data from sender

Window: 16 bits

The number of data octets beginning with the one indicated in the acknowledgment field
which the sender of this segment is willing to accept.

Checksum: 16 bits

The checksum field is the 16 bit one's complement of the one's complement sum of all 16
bit words in the header and text. If a segment contains an odd number of header and text
octets to be checksummed, the last octet is padded on the right with zeros to form a 16 bit
word for checksum purposes. The pad is not transmitted as part of the segment. While
computing the checksum, the checksum field itself is replaced with zeros.

The checksum also covers a 96 bit pseudo header conceptually prefixed to the TCP header.
This pseudo header contains the Source Address, the Destination Address, the Protocol, and
TCP length. This gives the TCP protection against misrouted segments. This information is
carried in the Internet Protocol and is transferred across TCP/Network interface in the
arguments or results of calls by the TCP on the IP.

+--------+--------+--------+--------+

| Source Address |

+--------+--------+--------+--------+

| Destination Address |

+--------+--------+--------+--------+
| Zero | PTCL | TCP Length |

+--------+--------+--------+--------+

The TCP Length is the TCP header length plus the data length in octets (this is not an
explicitly transmitted quantity, but is computed), and it does not count the 12 octets of the
pseudo header.

Urgent Pointer: 16 bits

This field communicates the current value of the urgent pointer as a positive offset from
the sequence number in this segment. The urgent pointer points to the sequence number of
the octet following the urgent data. This field is only be interpreted in segments with the
URG control bit set.

Options: variable

Options may occupy space at the end of the TCP header and are a multiple of 8 bits in
length. All options are included in the checksum. An option may begin on any octet
boundary. There are two cases for the format of an option:

Case 1: A single octet of option-kind.

Case 2: An octet of option-kind, an octet of option-length, and the actual option-data octets.

The option-length counts the two octets of option-kind and option-length as well as the
option-data octets.

Note that the list of options may be shorter than the data offset field might imply. The
content of the header beyond the End-of-Option option must be header padding (i.e.zero).

A TCP must implement all options. Currently defined options include (kind indicated in
octal):

Kind Length Meaning

---- ------ -------

0 - End of option list.


1 - No-Operation.

2 4 Maximum Segment Size.

Specific Option Definitions

End of Option List

+--------+

|00000000|

+--------+

Kind=0

This option code indicates the end of the option list. This might not coincide with the
end of the TCP header according to the Data Offset field. This is used at the end of all
options, not the end of each option, and need only be used if the end of the options would not
otherwise coincide with the end of the TCP header.

No-Operation

+--------+

|00000001|

+--------+

Kind=1

This option code may be used between options, for example, to align the beginning of a
subsequent option on a word boundary. There is no guarantee that senders will use this
option, so receivers must be prepared to process options even if they do not begin on a word
boundary.

Maximum Segment Size

+--------+--------+---------+--------+

|00000010|00000100| max seg size |

+--------+--------+---------+--------+

Kind=2 Length=4

Maximum Segment Size Option Data: 16 bits

If this option is present, then it communicates the maximum receive segment size at the
TCP which sends this segment.

This field must only be sent in the initial connection request (i.e., in segments with the
SYN control bit set). If this option is not used, any segment size is allowed.

Padding: variable

The TCP header padding is used to ensure that the TCP header ends and data begins on a
32 bit boundary. The padding is composed of zeros.

User Datagram Protocol


The User Datagram Protocol (UDP) is one of the core members of the Internet Protocol Suite,
the set of network protocols used for the Internet. With UDP, computer applications can send
messages, in this case referred to as datagrams, to other hosts on an Internet Protocol (IP)
network without requiring prior communications to set up special transmission channels or
data paths. UDP is sometimes called the Universal Datagram Protocol.

Packet structure

UDP provides application multiplexing (via port numbers) and integrity verification (via
checksum) of the header and payload. If transmission reliability is desired, it must be
implemented in the user's application.
bits 0 - 15 16 - 31

0 Source Port Destination Port

32 Length Checksum

64 Data

The UDP header consists of 4 fields. The use of two of those is optional in IPv4 (pink
background in table). In IPv6 only the source port is optional (see below).

Source port

This field identifies the sending port when meaningful and should be assumed to be
the port to reply to if needed. If not used, then it should be zero.

Destination port

This field identifies the destination port and is required.

Length

A 16-bit field that specifies the length in bytes of the entire datagram: header and
data. The minimum length is 8 bytes since that's the length of the header. The field
size sets a theoretical limit of 65,535 bytes (8 byte header + 65527 bytes of data) for a
UDP datagram. The practical limit for the data length which is imposed by the
underlying IPv4 protocol is 65,507 bytes.

Checksum

The 16-bit checksum field is used for error-checking of the header and data. The
algorithm for computing the checksum is different for transport over IPv4 and IPv6. If
the checksum is omitted in IPv4, the field uses the value all-zeros. This field is not
optional for IPv6.

Checksum computation

Checksum is the 16-bit one's complement of the one's complement sum of a pseudo
header of information from the IP header, the UDP header, and the data, padded with
zero octets at the end (if necessary) to make a multiple of two octets.

In other words, all 16-bit words are summed using one's complement arithmetic. The sum is
then one's complemented to yield the value of the UDP checksum field.
If the checksum calculation results in the value zero (all 16 bits 0) it should be sent as the
one's complement (all 1's).

The difference between IPv4 and IPv6 is in the data used to compute the checksum.

IPv4

When UDP runs over IPv4, the checksum is computed using a pseudo-header that contains
information from the IPv4 header:

bits 0 - 7 8 - 15 16 - 23 24 - 31

0 Source address

32 Destination address

64 Zeros Protocol UDP length

96 Source Port Destination Port

128 Length Checksum

160 Data

The source and destination addresses are those in the IPv4 header. The protocol is that for
UDP (see List of IP protocol numbers): 17. The UDP length field is the length of the UDP
header and data.

UDP checksum computation is optional for IPv4. If a checksum is not used it should be set to
the value zero.

IPv6

When UDP runs over IPv6, the checksum is mandatory. The method used to compute it is
changed as documented in RFC 2460:

Any transport or other upper-layer protocol that includes the addresses from the IP
header in its checksum computation must be modified for use over IPv6 to include the
128-bit IPv6 addresses.

When computing the checksum, a pseudo-header is used that mimics the IPv6 header:

bits 0 - 7 8 - 15 16 - 23 24 - 31
0

32
Source address
64

96

128

160
Destination address
192

224

256 UDP length

288 Zeros Next Header

320 Source Port Destination Port

352 Length Checksum

384 Data

The source address is the one in the IPv6 header. The destination address is the final
destination; if the IPv6 packet doesn't contain a Routing header, that will be the destination
address in the IPv6 header; otherwise, at the originating node, it will be the address in the last
element of the Routing header, and, at the receiving node, it will be the destination address in
the IPv6 header. The value of the Next Header field is the protocol value for UDP: 17. The
UDP length field is the length of the UDP header and data.

Difference between TCP and UDP Protocol

TCP (Transmission Control Protocol). UDP (User Datagram Protocol).


TCP is a connection-oriented protocol, a
connection can be made from client to A simpler message-based connectionless
server, and from then on any data can be protocol. With UDP you send
sent along that connection. messages(packets) across the network in
chunks.
Reliable – when you send a message along Unreliable – When you send a message,
a TCP socket, you know it will get there you don’t know if it’ll get there, it could
unless the connection fails completely. If it get lost on the way.
gets lost along the way, the server will re-
request the lost part. This means complete
integrity, things don’t get corrupted.
Ordered – if you send two messages along Not ordered – If you send two messages
a connection, one after the other, you know out, you don’t know what order they’ll
the first message will get there first. You arrive in.
don’t have to worry about data arriving in
the wrong order.
Heavyweight – when the low level parts of Lightweight – No ordering of messages, no
the TCP “stream” arrive in the wrong tracking connections, etc. It’s just fire and
order, resend requests have to be sent, and forget! This means it’s a lot quicker, and
all the out of sequence parts have to be put the network card / OS have to do very little
back together, so requires a bit of work to work to translate the data back from the
piece together. packets.

RESULT:
Thus the UDP/TCP protocols was studied successfully

You might also like