CN Lab Manual Updated
CN Lab Manual Updated
24
To write java programs to implement
a) Retrieving the IP address of the system.
b) Retrieving the IP address of the web page.
c) Downloading a file from http server.
d) Retrieving the current date and time of the machine.
Program:
import java.net.*;
class Myaddress
{
public static void main (String args[])
{
try
{
InetAddress address = InetAddress.getLocalHost();
System.out.println(address);
}
catch (UnknownHostException e)
{
System.out.println("Could not find this computer's address.");
}
}
Output:
$javac Myaddress.java
$java Myaddress
CS172/192.168.5.172
Program:
import java.net.*;
24
class Webaddress
{
public static void main (String args[])
{
try
{
InetAddress address = InetAddress.getByName("www.psnacet.org.in");
System.out.println(address);
}
catch (UnknownHostException e)
{
System.out.println("Could not find www.psnacet.edu.in ");
}
}
Output:
$javac Webaddress.java
$java Webaddress
192.268.5.11
24
System.out.println("Error"+e);
}}}
Output:
$javac Urldownload.java
$java Urldownload
Output:
$javac Getdatenow.java
$java Getdatenow
Now the date is : 2015/jan/08 02:13:24
CONCLUSION:
Thus, the java programs to implement
a) Retrieving the IP address of the system.
b) Retrieving the IP address of the web page.
c) Downloading a file from http server.
d) Retrieving the current date and time of the machine are being successfully executed and the
output is verified.
AIM:
To implement echo server and client in java using TCP sockets.
ALGORITHM:
24
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 servers 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.
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();
24
client.close();
sock.close();
System.out.println("Client Disconnected");
}
catch (IOException ioe)
{
System.err.println(ioe);
}
}
}
//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();
}
24
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
CONCLUSION:
Thus data from client to server is echoed back to the client to check reliability/noise level of the channel.
System.out.println("Client connected");
toClient = new PrintWriter(new BufferedWriter(new OutputStreamWriter(Clt.getOutputStream())), true);
fromClient = new BufferedReader(new InputStreamReader(Clt.getInputStream()));
fromUser = new BufferedReader(new InputStreamReader(System.in));
String CltMsg, SrvMsg;
while(true)
{
CltMsg= fromClient.readLine();
if(CltMsg.equals("end"))
break;
else
{
System.out.println("\nServer <<< " +CltMsg);
System.out.print("Message to Client : ");
SrvMsg = fromUser.readLine();
toClient.println(SrvMsg);
}
}
System.out.println("\nClient Disconnected");
fromClient.close();
toClient.close();
fromUser.close();
Clt.close();
Srv.close();
24
}
catch (Exception E)
{
System.out.println(E.getMessage());
}
}
}
// TCP Chat Client--tcpchatclient.java
import java.io.*;
import java.net.*;
class tcpchatclient
{
public static void main(String args[])throws Exception
{
Socket Clt;
PrintWriter toServer;
BufferedReader fromUser, fromServer;
try
{
if (args.length > 1)
{
System.out.println("Usage: java hostipaddr");
System.exit(-1);
}
if (args.length == 0)
Clt = new Socket(InetAddress.getLocalHost(),5555);
else
Clt = new Socket(InetAddress.getByName(args[0]),5555);
toServer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(Clt.getOutputStream())), true);
fromServer = new BufferedReader(new InputStreamReader(Clt.getInputStream()));
fromUser = new BufferedReader(new InputStreamReader(System.in));
String CltMsg, SrvMsg;
System.out.println("Type \"end\" to Quit");
while (true)
{
System.out.print("\nMessage to Server : ");
CltMsg = fromUser.readLine();
toServer.println(CltMsg);
if (CltMsg.equals("end"))
break;
SrvMsg = fromServer.readLine();
System.out.println("Client <<< " + SrvMsg);
}
}
catch(Exception E)
{
System.out.println(E.getMessage());
}
}
}
OUTPUT
24
Server:
$ javac tcpchatserver.java
$ java tcpchatserver
Server started
Client connected
Server <<< hi
Message to Client : hello
Server <<< how r u?
Message to Client : fine
Server <<< me too
Message to Client : bye
Client Disconnected
Client: $ javac tcpchatclient.java
$ java tcpchatclient
Type "end" to Quit
Message to Server : hi
Client <<< hello
Message to Server : how r u?
Client <<< fine
Message to Server : me too
Client <<< bye
Message to Server : end
RESULT
Thus both the client and server exchange data using TCP socket programming.
24
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 message
5. Read server's response
6. If ip address then display it else display "Domain does not exist"
7. Close the client socket
8. 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"};
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();
24
}
}
}
//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
24
Enter the hostname : youtube.com
IP Address: Host Not Found
RESULT
Thus domain name requests by the client are resolved into their respective logical address using lookup method.
24
4. Create an object for file writeclass named with in-txt to write onto the file
5. Pass the filename as that of command line argument.
6. Read the input from the client and print it
7. In the client side create a socket to connect to the server
8. Open a file using the file class object and read the contents of the file line by line in server side
9. Send the read content for the new file by server to the client
EXECUTION:
1. Write and compile two files separately
2. Run two files
3. Client send the file name, which is to be transferred and destination path to which the source file is
transferred as a command line arguments
4. Server reads the contents of the file and sends to the client.
5. At the client side the content is sent by server will be written into the new file.
Source Code :
ftpclient .java :
import java.io.*;
import java.net.*;
class ftpclient
{
public static void main(String args[])throws Exception
{
int i;
DatagramSocket ds=new DatagramSocket(2222);
byte b[]=new byte[2048];
BufferedReader dis=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the destin file name: ");
String tfile=dis.readLine();
File f=new File(tfile);
FileOutputStream fos=new FileOutputStream(f);
while(true)
{
DatagramPacket dp=new DatagramPacket(b,1024);
System.out.println("Waiting for File");
ds.receive(dp);
String s= new String(dp.getData(),0,0,dp.getLength());
for( int j=0;j<s.length();j++)
{
i=(int)s.charAt(j);
fos.write(i);
}
System.out.println("File Received");
break;
}
}
}
ftpserver.java:
import java.io.*;
import java.net.*;
class ftpserver
24
{
public static void main(String args[])throws Exception
{
int j=0;
DatagramSocket ds=new DatagramSocket(1111);
byte b[]=new byte[2048];
BufferedReader dis=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the source file name: ");
String sfile=dis.readLine();
File f=new File(sfile);
if(f.isFile())
System.out.println("source is present");
else
System.out.println("not present");
FileInputStream fis=new FileInputStream(f);
while(fis.available()!=0)
{
int i= fis.read();
b[j++]=(byte)i;
}
ds.send(new DatagramPacket(b,j,InetAddress.getLocalHost(),2222));
System.out.println("File was sent");
}
}
24
CONCLUSION:
Thus the java program to implement file transfer using FTP has been executed successfully and the output is
verified.
24
PROGRAM:
Clientfile.java:
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",1309);
DataInputStream din=new DataInputStream(clsct.getInputStream());
DataOutputStreamdout=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);
} }}
Serverfile.java:
import java.io.*; import java.net.*;
import java.util.*; class Serverfile
{ public static void main(String args[])
{
try
{
ServerSocketobj=new ServerSocket(1309);
while(true)
{
Socket obj1=obj.accept();
DataInputStream din=new DataInputStream(obj1.getInputStream());
DataOutputStreamdout=new DataOutputStream(obj1.getOutputStream());
String str=din.readLine();
FileReader f=new FileReader(str);
24
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
Client:
Enter the file name: hai.txt
Server :
Enter the new file: hello.txt
File content
24
CONCLUSION:
Thus the java program to implement file transfer using FTP has been executed successfully and the output is
verified.
stopreceive
import java.io.*;
import java.net.*;
class stopreceive
{
static final int port=8080;
public static void main(String args[])
{
try
{
InetAddress addr=InetAddress.getByName("Localhost");
Socket s=new Socket(addr,port);
int r=10,limit=0;
while(r!=limit)
24
{
if(r==limit-1)
{
BufferedReader in=new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(s.getOutputStream())),true);
String str=in.readLine();
System.out.println("\nFrame "+str+" has been received");
out.println(str);
System.out.println("\nAcknowledgement "+str+" has been sent");
break;
}
else
{
BufferedReader in=new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(s.getOutputStream())),true);
r=Integer.parseInt(in.readLine());
limit=Integer.parseInt(in.readLine());
System.out.println("\nFrame"+r+" has been received");
out.println(r);
System.out.println("\nAcknowledgement"+r+" has been sent");
}
}
}
catch(Exception e){ }
}
}
Stopsend
import java.io.*;
import java.net.*;
class stopsend{
static final int port=8080;
public static void main(String args[]){
try{
ServerSocket ss=new ServerSocket(port);
Socket s=ss.accept();
int no=0;
System.out.println("Enter the number of frames u want to transmit:");
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
int limit=Integer.parseInt(in.readLine());
while(no<limit)
{
if(no!=limit-1)
{
PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(s.getOutputStream())),true);
System.out.println("\nFrame"+no+" has been sent");
out.println(no);
out.println(limit);
BufferedReader brr=new BufferedReader(new InputStreamReader(s.getInputStream()));
System.out.println("\nAcknowledgement "+brr.readLine()+" has been received");
no=no+1;
}
24
else
{
PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(s.getOutputStream())),true);
System.out.println("\nFrame EOT has been sent");
String str="EOT";
out.println(str);
BufferedReader brr=new BufferedReader(new InputStreamReader(s.getInputStream()));
System.out.println("\nAcknowledgement "+brr.readLine()+" has been received");
no=no+1;
}
}
System.out.println("\nClosing");
s.close();
}
catch(Exception e){ }
}}
CONCLUSION:
24
Thus the java program to implement Stop and Wait protocolhas been executed successfully and the output is
verified.
AIM:
To simulate sliding window algorithm for packet-based data transmission.
DESIGN APPROACH:
A sliding window protocol is a feature of packet-based data transmission protocols. Sliding window
protocols are used where reliable in-order delivery of packets is required, such as in the Data Link
Layer(OSI Model) as well as in the Transmission Control Protocol(TCP).
ALGORITHM:
Sender:
7. Import the required class packages from java toolkit.
8. Initialize the sender with user defined socket.
9. Read the number of frames to be transmitted.
10. Send a frame to the receiver.
11. The sender does not wait for the acknowledgement from the receiver.
12. It continues sending its frames.
Receiver:
4. Import the required class packages from java toolkit
5. Initialize the sender with user defined socket.
6. If a frame is received send an acknowledgement to the sender.
//SENDER PROGRAM
import java.net.*;
import java.io.*;
import java.rmi.*;
public class slidesender
{
public static void main(String a[])throws
Exception
{
ServerSocket ser=new ServerSocket(10);
Socket s=ser.accept();
DataInputStream in=new DataInputStream(System.in);
DataInputStream in1=new DataInputStream(s.getInputStream());
String sbuff[]=new String[8];
PrintStream p;
int sptr=0,sws=8,nf,ano,i;
String ch;
24
do
{
p=new PrintStream(s.getOutputStream());
System.out.print("Enter the no. of frames : ");
nf=Integer.parseInt(in.readLine());
p.println(nf);
if(nf<=sws-1)
{
//RECEIVER PROGRAM
import java.net.*;
import java.io.*;
class slidreceiver
{
public static void main(String a[])throws Exception
{
Socket s=new Socket(InetAddress.getLocalHost(),10);
DataInputStream in=new DataInputStream(s.getInputStream());
PrintStream p=new PrintStream(s.getOutputStream());
int i=0,rptr=-1,nf,rws=8;
String rbuf[]=new String[8];
String ch; System.out.println();
do
24
{
nf=Integer.parseInt(in.readLine());
if(nf<=rws-1)
{
for(i=1;i<=nf;i++)
{
rptr=++rptr%8;
rbuf[rptr]=in.readLine();
System.out.println("The received Frame " +rptr+" is : "+rbuf[rptr]);
}
rws-=nf;
System.out.println("\nAcknowledgment sent\n");
p.println(rptr+1); rws+=nf; }
else
break;
ch=in.readLine();
}
while(ch.equals("yes"));
}
}
RESULT:
Thus the sliding window algorithm was executed successfully and the result was noted after careful observation
and verified.
24
Ex.N0: 6 SIMULATION OF ARP/RARP
AIM:
To write a C program to simulate the concept of ARP and RARP through the given data.
DESIGN APPROACH:
24
scanf("%s",str);
while(i<4)
{
if(strcmp(str,ip[i])==0)
{
printf("The corresponding MAC address is %s",mac[i]);
break;
}
i++;
}
if(i>=4)
printf("Invalid address");
break;
case 2:
printf("Enter the MAC address:");
scanf("%s",str);
while(i<4)
{
if(strcmp(str,mac[i])==0)
{
printf("The corresponding IP address is %s",ip[i]);
break;
}
i++;
}
if(i>=4)
printf("Invalid address");
break;
default:
exit(0);
}
}
}
EXPECTED INPUT/OUTPUT:
1.ARP
2.RARP
3.Exit
Enter ur choice: 1
Enter the IP address:192.32.168.09
The corresponding MAC address is AA-BB-CC-DD-EC-10
1.ARP
2.RARP
3.Exit
Enter ur choice: 2
Enter the IP address: AA-BB-CC-DD-EC-10
The corresponding MAC address is 192.32.168.09
1.ARP
2.RARP
3.Exit
24
Enter ur choice: 3
OBTAINED INPUT/OUTPUT:
1.ARP
2.RARP
3.Exit
Enter ur choice: 1
Enter the IP address:255.255.255.255
The corresponding MAC address is DC-28-16-F4-D1-0A
1.ARP
2.RARP
3.Exit
Enter ur choice: 2
Enter the MAC address:DC-28-16-F4-D1-0A
The corresponding IP address is 255.255.255.255
1.ARP
2.RARP
3.Exit
Enter ur choice: 2
Enter the MAC address:df-56-4d
Invalid address
1.ARP
2.RARP
3.Exit
Enter ur choice: 3
24
ONCLUSION:
The C Program to simulate the concept of ARP and RARP was written and executed.
AIM:
ALGORITHM:
2) Once client has been accepted using accept method. It will return a new socket object.
4) Everytime it will read the packet containing message and will send reply to client through the server. It
will be always running. Since it should reply for all the packets from the client.
5) In the client side socket is created and connected with server Socket machine.
6) After the connection is established the packet which contains the message is sending to the server
through the socket and reply for the package is used.
PROGRAM:
SERVER:
import java.net.*;
import java.io.*;
class serverping
{
public static void main(String args[])throws Exception
{
String msg;
ServerSocket sersock=new ServerSocket(4444);
PrintStream out;
int i=0;
System.out.println(server connected);
try
{
Socket s=sersock.accept();
24
out = new PrintStream(s.getOutputStream());
DataInputStream in=new DataInputStream(s.getInputStream()):
while(i<4)
{
msg=in.readLine();
System.out.println(msg);
if(msg.equals( ))
break;
i++;
}
out.println(received);
out.println(i);
}
catch(Exception e)
{
}
}
}
CLIENT:
import java.net.*;
import java.io.*;
class clientping
{
public static void main(String args[])throws Exception
{
Socket s;
PrintStream out;
InetAddress addr;
int i=0;int j;
String msg;
String name;
try
{
if(args.length==0)
addr=InetAddress.getLocalHost();
else
addr= InetAddress.getByName(args[0]);
System.out.println(CONNECTED);
s=new socket(addr,4444);
out = new PrintStream(s.getOutputStream());
DataInputStream in=new DataInputStream(s.getInputStream()):
for(i=0;i<4;i++)
{
24
out.println(Packet +i);
System.out.println(Reply from +addr+:byte=32);
}
msg=in.readLine();
while(!msg.equals(received))
msg=in.readLine();
j=Integer.parseInt(in.readLine());
System.out.println(ping statistics for +addr);
System.out.println(packet send=+i Received=+j);
}
catch(Exception e)
{
}
}
}
OUTPUT:
SERVER:
D:\java> javac serverping.java
D:\java>java serverping
Server connected
Packet 0
Packet 1
Packet 2
Packet 3
D:\java>
CLIENT:
D:\java> javac clientping.java
D:\java>java clientping 192.168.5.86
CONNECTED
Reply from/192.168.5.86:byte=32
Reply from/192.168.5.86:byte=32
Reply from/192.168.5.86:byte=32
Reply from/192.168.5.86:byte=32
ping statistics for/192.168.5.86
packet send=4 Receive=4
D:\java>
CONCLUSION:
Thus the java program for implementing ping was implemented and executed successfully.
24
7b) Implementation of Traceroute
AIM:
To Write The java program for simulating traceroute commands
PROBLEM DESCRIPTION:
Traceroute is a computer network diagnostic tool for displaying the route (path) and measuring transit
delays of packets across an Internet Protocol (IP) network. The history of the route is recorded as the round-trip
times of the packets received from each successive host (remote node) in the route (path); the sum of the mean
times in each hop indicates the total time spent to establish the connection. Traceroute proceeds unless all
(three) sent packets are lost more than twice, then the connection is lost and the route cannot be evaluated. Ping,
on the other hand, only computes the final round-trip times from the destination point.
PROGRAM:
import java.io.*;
import java.net.*;
class traceroute
{
public static void main(String args[])throws Exception
{
try
{
BufferedReader in=null;
FileOutputStream fout;
FileInputStream fin;
Runtime r=Runtime.getRuntime();
Process p=r.exec("tracert 192.168.5.214");
in=new BufferedReader(new InputStreamReader(p.getInputStream()));
fout=new FileOutputStream("out.data");
PrintWriter pw=new PrintWriter(fout,true);
String line;
while((line=in.readLine())!=null)
{
System.out.println(line);
pw.println(line);
}
fin=new FileInputStream("out.data");
BufferedReader bin1=new BufferedReader(new InputStreamReader(System.in));
BufferedReader bin=new BufferedReader(new InputStreamReader(fin));
String l,l1,l2;
l1=bin1.readLine();
l1=" "+l1;
l=bin.readLine();
while((l=bin.readLine())!=null)
{
if(l.startsWith(l1))
{
l2=l.substring(25,41);
System.out.println(l2);
24
break;
}
}
in.close();
}
catch(IOException e){}
}
}
CONCLUSION:
Thus the program to implement traceroute command was executed successfully.
24
Ex.No:8 Write a program to implement RPC (Remote Procedure Call)
AIM:
To write a java program to implement RPC (remote procedure call
ALGORITHM :
PROGRAM:
CLIENT :
import java.io.*;
import java.net.*;
import java.util.*;
class Clientrpc
{
public static void main(String args[])
{ try
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
Socket clsct=new Socket("127.0.0.1",139);
DataInputStream din=new DataInputStream(clsct.getInputStream());
DataOutputStream dout=new DataOutputStream(clsct.getOutputStream());
System.out.println("Enter String");
String str=in.readLine();
dout.writeBytes(str+'\n');
clsct.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
}
24
SERVER:
import java.io.*;
import java.net.*;
import java.util.*;
class Serverrpc
{
public static void main(String args[])
{ try
{
ServerSocket obj=new ServerSocket(139);
while(true)
{
Socket obj1=obj.accept();
DataInputStream din=new DataInputStream(obj1.getInputStream());
DataOutputStream dout=new DataOutputStream(obj1.getOutputStream());
String str=din.readLine();
Process p=Runtime.getRuntime().exec(str);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
OUTPUT:
Server
Y:\networks\remote>java Serverrpc
Client
Y:\networks\remote>java Clientrpc
Enter String calc
CONCLUSION:
Thus the program was implementing to implement RPC (remote procedure call
24
Ex.No:9 IMPLEMENTATION OF SUBNETTING
AIM:
To write a program to implement subnetting and find the subnet masks.
ALGORITHM :
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 subnet mask is = +mask);
//Calculation of first address and last address
24
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;
}
}
24
OUTPUT :
CONCLUSION:
Thus the Program was displayed implement subnetting and find the subnet masks.
24
Ex. No:10. Perform a case study about the different routing algorithms to select the
Network path with its optimum and economical during data transfer.
i. Link State routing
Aim:
To study the link state routing
In packet switching networks, routing directs packet forwarding (the transit of logically addressed network
packets from their source toward their ultimate destination) through intermediate nodes. Intermediate nodes are
typically network hardware devices such as routers, bridges, gateways, firewalls, or switches. General-purpose
computers can also forward packets and perform routing, though they are not specialized hardware and may suffer
from limited performance. The routing process usually directs forwarding on the basis of routing tables which
maintain a record of the routes to various network destinations. Thus, constructing routing tables, which are held in
the router's memory, is very important for efficient routing. Most routing algorithms use only one network path at a
time. Multipath routing techniques enable the use of multiple alternative paths.
In case of overlapping/equal routes, the following elements are considered in order to decide which routes
get installed into the routing table (sorted by priority):
1. Prefix-Length: where longer subnet masks are preferred (independent of whether it is within a routing protocol or
over different routing protocol)
2. Metric: where a lower metric/cost is preferred (only valid within one and the same routing protocol)
3. Administrative distance: where a lower distance is preferred (only valid between different routing protocols)
Routing, in a more narrow sense of the term, is often contrasted with bridging in its assumption that network
addresses are structured and that similar addresses imply proximity within the network. Structured addresses allow a
single routing table entry to represent the route to a group of devices. In large networks, structured addressing
(routing, in the narrow sense) outperforms unstructured addressing (bridging). Routing has become the dominant
form of addressing on the Internet. Bridging is still widely used within localized environments.
ii. Flooding
Floodings a simple routing algorithm in which every incoming packet is sent through every outgoing link
except the one it arrived on. Flooding is used in bridging and in systems such as Usenet and peer-to-peer file sharing
and as part of some routing protocols, including OSPF, DVMRP, and those used in ad-hoc wireless networks. There
are generally two types of flooding available, Uncontrolled Flooding and Controlled Flooding. Uncontrolled
Flooding is the fatal law of flooding. All nodes have neighbors and route packets indefinitely. More than two
neighbors creates a broadcast storm. Controlled Flooding has its own two algorithms to make it reliable, SNCF
(Sequence Number Controlled Flooding) and RPF (Reverse Path Flooding). In SNCF, the node attaches its own
address and sequence number to the packet, since every node has a memory of addresses and sequence numbers. If it
receives a packet in memory, it drops it immediately while in RPF, the node will only send the packet forward. If it is
received from the next node, it sends it back to the sender.
Algorithm
There are several variants of flooding algorithm. Most work roughly as follows:
1. Each node acts as both a transmitter and a receiver.
2. Each node tries to forward every message to every one of its neighbors except the source node.
24
This results in every message eventually being delivered to all reachable parts of the network.
Algorithms may need to be more complex than this, since, in some case, precautions have to be taken to avoid
wasted duplicate deliveries and infinite loops, and to allow messages to eventually expire from the system. A variant
of flooding called selective flooding partially addresses these issues by only sending packets to routers in the same
direction. In selective flooding the routers don't send every incoming packet on every line but only on those lines
which are going approximately in the right direction.
Advantages
f a packet can be delivered, it will (probably multiple times).
Since flooding naturally utilizes every path through the network, it will also use the shortest path.
Disadvantages
Flooding can be costly in terms of wasted bandwidth. While a message may only have one destination it has to be
sent to every host. In the case of a ping flood or a denial of service attack, it can be harmful to the reliability of a
computer network.
Messages can become duplicated in the network further increasing the load on the networks bandwidth as well as
requiring an increase in processing complexity to disregard duplicate messages.
Duplicate packets may circulate forever, unless certain precautions are taken:
Use a hop count or a time to live count and include it with each packet. This value should take into account the
number of nodes that a packet may have to pass through on the way to its destination.
Have each node keep track of every packet seen and only forward each packet once
Enforce a network topology without loops
The term distance vector refers to the fact that the protocol manipulates vectors (arrays) of distances to other
nodes in the network. The vector distance algorithm was the original ARPANET routing algorithm and was also used
in the internet under the name of RIP (Routing Information Protocol).
Examples of distance-vector routing protocols include RIPv1 and RIPv2 and IGRP.
Method
Routers using distance-vector protocol do not have knowledge of the entire path to a destination. Instead they
use two methods:
1. Direction in which router or exit interface a packet should be forwarded.
2. Distance from its destination
Distance-vector protocols are based on calculating the direction and distance to any link in a network.
"Direction" usually means the next hop address and the exit interface. "Distance" is a measure of the cost to reach a
certain node. The least cost route between any two nodes is the route with minimum distance. Each node maintains a
vector (table) of minimum distance to every node. The cost of reaching a destination is calculated using various route
24
metrics. RIP uses the hop count of the destination whereas IGRP takes into account other information such as node
delay and available bandwidth.
Updates are performed periodically in a distance-vector protocol where all or part of a router's routing table
is sent to all its neighbors that are configured to use the same distance-vector routing protocol. RIP supports cross-
platform distance vector routing whereas IGRP is a Cisco Systems proprietary distance vector routing protocol. Once
a router has this information it is able to amend its own routing table to reflect the changes and then inform its
neighbors of the changes. This process has been described as routing by rumor because routers are relying on the
information they receive from other routers and cannot determine if the information is actually valid and true. There
are a number of features which can be used to help with instability and inaccurate routing information.
EGP and BGP are not pure distance-vector routing protocols because a distance-vector protocol calculates
routes based only on link costs whereas in BGP, for example, the local route preference value takes priority over the
link cost.
Count-to-infinity problem
The BellmanFord algorithm does not prevent routing loops from happening and suffers from the count-to-
infinity problem. The core of the count-to-infinity problem is that if A tells B that it has a path somewhere, there is
no way for B to know if the path has B as a part of it. To see the problem clearly, imagine a subnet connected like A
BCDEF, and let the metric between the routers be "number of jumps". Now suppose that A is taken offline. In
the vector-update-process B notices that the route to A, which was distance 1, is down B does not receive the
vector update from A. The problem is, B also gets an update from C, and C is still not aware of the fact that A is
down so it tells B that A is only two jumps from C (C to B to A), which is false. This slowly propagates through the
network until it reaches infinity (in which case the algorithm corrects itself, due to the relaxation property of
BellmanFord).
CONCLUSION:
Thus the Perform a case study about the different routing algorithms to select the Network path with its
optimum and economical during data transfer was completed.
24
Ex.No.11. Study of Network simulator (NS).and Simulation of Congestion
Control Algorithms using NS
Aim:
To Study of Network simulator (NS).and Simulation of Congestion Control Algorithms using NS
Ns overview
Ns Status
Periodical release (ns-2.26, Feb 2003)
Platform support
FreeBSD, Linux, Solaris, Windows and Mac
Ns functionalities
Routing, Transportation, Traffic sources, Queuing
Disciplines, QoS
Wireless
Ad hoc routing, mobile IP, sensor-MAC
Tracing, visualization and various utilities
NS (Network Simulators)
Most of the commercial simulators are GUI driven, while some network simulators are CLI driven. The
network model / configuration describes the state of the network (nodes,routers,switches, links) and the events (data
transmissions, packet error etc.). An important output of simulations are the trace files. Trace files log every packet,
every event that occurred in the simulation and are used for analysis. Network simulators can also provide other
tools to facilitate visual analysis of trends and potential trouble spots.
Most network simulators use discrete event simulation, in which a list of pending "events" is stored, and
those events are processed in order, with some events triggering future eventssuch as the event of the arrival of a
packet at one node triggering the event of the arrival of that packet at a downstream node.
Simulation of networks is a very complex task. For example, if congestion is high, then estimation of the
average occupancy is challenging because of high variance. To estimate the likelihood of a buffer overflow in a
network, the time required for an accurate answer can be extremely large. Specialized techniques such as "control
variates" and "importance sampling" have been developed to speed simulation.
24
Network simulators serve a variety of needs. Compared to the cost and time involved in setting up an entire
test bed containing multiple networked computers, routers and data links, network simulators are relatively fast and
inexpensive. They allow engineers, researchers to test scenarios that might be particularly difficult or expensive to
emulate using real hardware - for instance, simulating a scenario with several nodes or experimenting with a new
protocol in the network. Network simulators are particularly useful in allowing researchers to test new networking
protocols or changes to existing protocols in a controlled and reproducible environment. A typical network simulator
encompasses a wide range of networking technologies and can help the users to build complex networks from basic
building blocks such as a variety of nodes and links. With the help of simulators, one can design hierarchical
networks using various types of nodes like computers, hubs, bridges, routers, switches, links, mobile units etc.
Various types of Wide Area Network (WAN) technologies like TCP, ATM, IP etc. and Local Area Network
(LAN) technologies like Ethernet, token rings etc., can all be simulated with a typical simulator and the user can test,
analyze various standard results apart from devising some novel protocol or strategy for routing etc. Network
simulators are also widely used to simulate battlefield networks in Network-centric warfare.
There are a wide variety of network simulators, ranging from the very simple to the very complex.
Minimally, a network simulator must enable a user to represent a network topology, specifying the nodes on the
network, the links between those nodes and the traffic between the nodes. More complicated systems may allow the
user to specify everything about the protocols used to handle traffic in a network. Graphical applications allow users
to easily visualize the workings of their simulated environment. Text-based applications may provide a less intuitive
interface, but may permit more advanced forms of customization.
Packet loss
Occurs when one or more packets of data travelling across a computer network fail to reach their destination.
Packet loss is distinguished as one of the three main error types encountered in digital communications; the other
two being bit error and spurious packets caused due to noise.
Packets can be lost in a network because they may be dropped when a queue in the network node overflows.
The amount of packet loss during the steady state is another important property of a congestion control scheme. The
larger the value of packet loss, the more difficult it is for transport layer protocols to maintain high bandwidths, the
sensitivity to loss of individual packets, as well as to frequency and patterns of loss among longer packet sequences
is strongly dependent on the application itself.
Throughput
This is the main performance measure characteristic, and most widely used. In communication networks,
such as Ethernet or packet radio, throughput or network.
Throughput is the average rate of successful message delivery over a communication channel. The
throughput is usually measured in bits per second (bit/s or bps), and sometimes in data packets per second or data
packets per time slot his 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 value of delay, the more difficult it is for transport layer
protocols to maintain high bandwidths. We will calculate end to end delay
Queue Length
A queuing system in networks can be described as packets arriving for service, waiting for service if it is not
immediate, and if having waited for service, leaving the system after being served. Thus queue length is very
24
important characteristic to determine that how well the active queue management of the congestion control algorithm
has been working.
CONCLUSION:
Thus the study of Network simulator (NS2) was studied.
24