acn practicals

78
100280116026 8 TH I.T(A) L.D College Of Engineering ADVANCE COMPUTER NETWORKS PRACTICALS 1. Setup a WIFI network. Setting up a Wi-Fi network will allow all your computers (and any guests you want to share your network with) to get online without needing to plug in an Ethernet cable. A wireless network can also make it easy to stream music and video to any device on the network. Still got some old PCs that don't have wireless cards? That's okay, most Wi-Fi routers have a few Ethernet ports as well. Before we get started building the network, you will need to purchase a wireless router, as well as some wireless network interface cards if your computers don't already have them built in. Once you have your router the next step is choosing a good location. Try to install your router in a central location so that every room in your house is covered by the Wi-Fi signal. To set up the network, follow these steps: Step 1: Connect Everything Step 2: Turning it on Step 3: Set up the network Step 4: Turn on encryption Page | 1

Upload: krupanick24

Post on 20-May-2017

221 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

ADVANCE COMPUTER NETWORKS

PRACTICALS

1. Setup a WIFI network.

Setting up a Wi-Fi network will allow all your computers (and any guests you want to share your network with) to get online without needing to plug in an Ethernet cable. A wireless network can also make it easy to stream music and video to any device on the network. Still got some old PCs that don't have wireless cards? That's okay, most Wi-Fi routers have a few Ethernet ports as well.

Before we get started building the network, you will need to purchase a wireless router, as well as some wireless network interface cards if your computers don't already have them built in.

Once you have your router the next step is choosing a good location. Try to install your router in a central location so that every room in your house is covered by the Wi-Fi signal.

To set up the network, follow these steps:

Step 1: Connect Everything Step 2: Turning it on Step 3: Set up the network Step 4: Turn on encryption Step 5: Connect

Step 1: Connect Everything

Connect your existing modem to the wireless router using an Ethernet cable (be sure to connect the modem to the port labelled "Internet" on most routers, otherwise you may not be able to connect to the internet. Refer to the documentation of your router). This moves the internet

Page | 1

Page 2: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

connection from your modem to the wireless router. Once that's done, plug your PC into the back of the router using the Ethernet jacks. We'll need this connection to configure the Wi-Fi network.

Step 2: Turning it on

Turn on your modem first, then the wireless router and finally the computer. The order is important since each successive device need to detect the connection to the one that precedes it in the chain.

Step 3: Set up the network

Check the documentation that came with your wireless router for the default IP address used by the device. Launch your computer's Web browser and head to IP address of the router.

Page | 2

Page 3: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

You should see a login window requiring a username and password. The default values should be in your router's documentation.

Once you've logged in, you'll see your router's settings page. The first step is make sure you change the default admin password so other users won't be able to login to the settings page and reconfiguring the router.

The next thing you'll probably want to do is changing the SSID value of the router. This is the name broadcasted by the router to identify it across the network. Chose a unique SSID name and save your changes (this will likely reboot the router).

Scan for wireless networks and see which channels are in use. Try to find a free one, or one with minimal interference. In channel 1-11 a channel is only completely free when there is nothing on the channel and three channels up or down, so 'minimal interference' is usually what you have to settle for. The tool you use to find your network from your laptop might list channels and some idea of signal strength of other networks. Or you could use a dedicated wireless scanning application. For Windows versions: use Netstumbler scanning software, for Linux: use kismet (not very easy to set up though).

Step 4: Turn on encryption

Right now your Wi-Fi network is up and running, but anyone can access it. If that doesn't bother you, then you're done. However, you might want to enable some sort of Wi-Fi encryption to protect your network and make sure that only trusted computers have access.

Different routers support different levels of encryption so what you use is up to you, though we should note that WEP encryption is trivially easy to defeat; you'll be much better off using WPA Personal or WPA Enterprise if your router supports it.

Page | 3

Page 4: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

Step 5: Connect

Once you're happy with your settings, disconnect your PC and then head to your network settings tool and you should see your new Wi-Fi network listed under available networks. Select your network and type in your password (if you're using one) to connect.

2. Study of network simulator 3.

Similar to NS2, NS3 is also an open sourced discrete-event network simulator which targets primarily for research and educational use. NS3 is licensed under the GNU GPLv2 license, and is available for research and development.

Overview

NS3 is designed to replace the current popular NS2. However, NS3 is not an updated version of NS2 since that NS3 is a new simulator and it is not backward-compatible with NS2.

Main features

The basic idea of NS3 comes from several different network simulators including NS2, YANS [YANS], and GTNetS [GTNetS]. The major difference lying between NS3 and NS2 includes:

(1) Different software core: The core of NS3 is written in C++ and with Python scripting interface (compared with OTcl in NS2). Several advanced C++ design patterns are also used.

(2) Attention to realism: Protocol entities are designed to be closer to real computers.

Page | 4

Page 5: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

(3) Software integration: Support the incorporation of more open-source networking software and reduce the need to rewrite models for simulation;

(4) Support for virtualization: Lightweight virtual machines are used. Figure 3 gives an example virtualization testbed of NS3.

Figure 1. Testbeds interconnect NS3 stacks

(5) Tracing architecture: NS3 is developing a tracing and statistics gathering framework trying to enable customization of the output without rebuilding the simulation core.

Through the comparison between NS2 and NS3, we can summarize the NS 3' s features as follows:

1. Modular, documented core

2. C++ programs and Python scripting

3. Alignment with real systems

4. Software integration

5. Virtualization and Testbed integration

6. Attribute system

7. Updated models

Page | 5

Page 6: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

Recent developments and its future

However, NS3 is still in the process and some major challenges still remain for NS3 to solve. The biggest one is that NS3 needs participation from the research community. Firstly, the simulation credibility needs to be improved. We know that one of the limitations of simulations, in general, is that it often suffers from lack of credibility. Generally there are four points that are important for NS3 to solve this problem. They are:

a) Hosting NS3 code and scripts for published work

b) Tutorials on how to do things right

c) Flexible means to configure and record values

d) Support for ported code should make model validation easier and more credible

Secondly, NS3 is intended to replicate the successful mode of NS 2 in which a lot of different organizations contributed to the models and components based on the framework of NS2. The following figure illustrates this status:

Figure 2. NS2 contributions model

Thirdly, NS3 need a lot of specialized maintainers in order to let the NS3 have the advantages as the commercial OPNET network simulators which is documented well. Specialized maintainers can play a key part in the system. In

Page | 6

Page 7: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

NS3, the active maintainers are required to respond to the user questions and bug reports, and help to test and validating the system.

All in all, NS-3 is an active open-source project and it is still under development. It has several simulator features designed to aid current Internet research.

3.Write a program for sending message from client to single server and server reply the same message to that client.(Echo client and echo server).

SERVER:

import java.io.*;import java.net.*;importjava.util.*;

classHelloServer{

public static void main(String args[]){

try{

ServerSocketobj = new ServerSocket(8189);Socket s = obj.accept();

try{

InputStream in = s.getInputStream();OutputStream out = s.getOutputStream();

Scanner sin = new Scanner(in);

PrintWriter pout = new PrintWriter(out,true);pout.println("Msg Accept From The Client");

String str = sin.nextLine();System.out.println("String is: "+str);

Page | 7

Page 8: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

}finally{

s.close();}

}catch(Exception e){

System.out.println(e);}

}}

CLIENT:

import java.io.*;import java.net.*;importjava.util.*;

classHelloClient{

public static void main(String args[]){

try{

Socket s =new Socket("localhost",8189);

try{

InputStream in = s.getInputStream();OutputStream out = s.getOutputStream();

Scanner sin = new Scanner(System.in);PrintWriter pout = new PrintWriter(out,true);

System.out.println("Enter Yaou Message: ");

String str = sin.nextLine();

Page | 8

Page 9: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

pout.println(str);

}finally{

s.close();}

}catch(Exception e){

System.out.println(e);}

}}

OUTPUT:

Z:\KRUPA_sem8\LDCE\ACN\Program-3>javac H*.java

Z:\KRUPA_sem8\LDCE\ACN\Program-3>java HelloServerString is: Hello

Z:\KRUPA_sem8\LDCE\ACN\Program-3>java HelloClientEnter Your Message:Hello

Page | 9

Page 10: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

4.Write a program for date and time client and server. (Using UDP and TCP).

// Date Client

importjava.util.*;import java.net.*;import java.io.*;

public class DTClient{

public static void main(String args[]){

try{

Socket s = new Socket("localhost",8081);try{

InputStream in = s.getInputStream();OutputStream out = s.getOutputStream();

Scanner sin = new Scanner(in);PrintWriter pout = new PrintWriter(out,true);

String str = sin.nextLine();

pout.println(str);

System.out.println("The Current Date is : "+str);}finally{

s.close();}

}catch(Exception e){

e.printStackTrace();}

}}

Page | 10

Page 11: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

// Date Server

importjava.util.*;import java.net.*;import java.io.*;

public class DTServer{

public static void main(String args[]){

try{

ServerSocketss = new ServerSocket(8081);Socket s1 = ss.accept();try{

InputStream in = s1.getInputStream();OutputStream out = s1.getOutputStream();

Scanner sin = new Scanner(in);PrintWriter pout = new PrintWriter(out,true);

Date date = new Date();

pout.println(date);}finally{

s1.close();}

}catch(Exception e){

System.out.println(e);}

}}

Page | 11

Page 12: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

OUTPUT:

Z:\KRUPA_sem8\LDCE\ACN\Program-4>javac DTServer.javaZ:\KRUPA_sem8\LDCE\ACN\Program-4>javac DTClient.javaZ:\KRUPA_sem8\LDCE\ACN\Program-4>java DTServer

Z:\KRUPA_sem8\LDCE\ACN\Program-4>java DTClientThe Current Date is: Fri Aug 27 11:30:16 GMT+05:30 2010

Page | 12

Page 13: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

5. Write a program for sending n numbers from client to server and server reply the sorted data to that client. (Using UDP and TCP).

//Client Side: ---------------------import java.io.*;import java.net.*;importjava.util.*;importjava.lang.*;

public class SortingClie{

public static void main(String args[]){

try{

Socket s2 = new Socket("localhost",8188);try{

InputStreaminstr = s2.getInputStream();OutputStreamoutstr= s2.getOutputStream();Scanner sin = new Scanner (System.in);int r=args.length;int no[] = new int[r];System.out.println("your range is:" + r);for(inti=0;i<r;i++){

no[i]=Integer.parseInt(args[i]);}for(inti=0;i<r;i++){

System.out.println("The no is:==>>"+no[i]);

}PrintWritersout = new PrintWriter(outstr,true);sout.println(r);for(inti=0;i<r;i++){

sout.println(no[i]);}

Page | 13

Page 14: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

Scanner sin11 = new Scanner(instr);System.out.println("The sorted array is:>>");for(inti=0;i<r;i++){

no[i]=sin11.nextInt();System.out.println("The no is:=>>" +no[i]);

}

}finally{

s2.close();}

}catch(IOException e){

System.out.println("Error occured");}

}}

//Server Side: ------------------import java.io.*;import java.net.*;importjava.util.*;

public class SortingSer{

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

ServerSocket s = new ServerSocket(8188);Socket incoming = s.accept();try{

InputStreaminstream = incoming.getInputStream();OutputStreamoutstream = incoming.getOutputStream();Scanner sin1 = new Scanner(instream);int x=sin1.nextInt();System.out.println("The data is retrived...");

Page | 14

Page 15: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

int y[]= new int[x+1];

for(inti=0;i<x;i++){

y[i]=sin1.nextInt();}for(inti=0;i<x;i++){

for(int j=i+1;j<x;j++){

if(y[i] < y[j]){

inttemp=y[i];y[i]=y[j];y[j]=temp;

}}

}PrintWriter pout = new PrintWriter(outstream,true);for(inti=0;i<x;i++){

pout.println(y[i]);}

}finally{

incoming.close();}

}catch(Exception e){

System.out.println("Error occured" + e);}}

}

Page | 15

Page 16: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

OUTPUT:

Z:\KRUPA_sem8\LDCE\ACN\Program-5>javac *.java

Z:\KRUPA_sem8\LDCE\ACN\Program-5>java SortingSerThe data is retrived...

Z:\KRUPA_sem8\LDCE\ACN\Program-5>java SortingClie 7 1 15 8 9 2 20

Your range is:7The no is:==>>7The no is:==>>1The no is:==>>15The no is:==>>8The no is:==>>9The no is:==>>2The no is:==>>20

The sorted array is:>>The no is:=>>20The no is:=>>15The no is:=>>9The no is:=>>8The no is:=>>7The no is:=>>2The no is:=>>1

Page | 16

Page 17: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

6. Write a program for sending two numbers and one operator to server and server reply theoutput of that operation to the client. (Using UDP datagram).

SERVER:import java.io.*;importjava.lang.*;import java.net.*;importjava.util.*;classServer_opr{

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

int no1,no2;charopr;doubleans;ServerSocket s=new ServerSocket(4567);System.out.println("Waiting for connection...");Socket skt=s.accept();System.out.println("connection Established....");

InputStreamops=skt.getInputStream();DataInputStream din=new DataInputStream(ops);

OutputStream in=skt.getOutputStream();DataOutputStreamdout=new DataOutputStream(in);

no1=din.readInt();no2=din.readInt();opr=din.readChar();

switch(opr){case '+':

ans=no1+no2;dout.writeDouble(ans);break;

case '-':ans=no1-no2;dout.writeDouble(ans);

Page | 17

Page 18: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

break;case '*':

ans=no1*no2;dout.writeDouble(ans);break;

case '/':ans=(double)no1/(double)no2;dout.writeDouble(ans);break;

default:break;

}din.close();dout.close();

}}

CLIENT:

import java.io.*;import java.net.*;importjava.util.*;classClient_opr{

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

int no1,no2;String opr;doubleans;Socket s=new Socket("localhost",4567);

InputStream in=s.getInputStream();DataInputStream dim=new DataInputStream(System.in);

InputStream in1=s.getInputStream();DataInputStream dim1=new DataInputStream(in1);

DataOutputStreamdout=new DataOutputStream(s.getOutputStream());

System.out.println("Enter First number : "); no1=Integer.parseInt(dim.readLine());

Page | 18

Page 19: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

dout.writeInt(no1);

System.out.println("Enter Second number : "); no2=Integer.parseInt(dim.readLine());

dout.writeInt(no2);

System.out.println("Enter Operator : ");opr=dim.readLine();dout.writeChars(opr);

ans=dim1.readDouble();System.out.println("Answer is : " +ans);

dim.close();dim1.close();dout.close();

}}

OUTPUT:

Z:\KRUPA_sem8\LDCE\ACN\Program-6>javac *.java

Z:\KRUPA_sem8\LDCE\ACN\Program-6>Server_opr

Z:\KRUPA_sem8\LDCE\ACN\Program-6>Client_opr

Enter First number:9Enter Second number:7Enter Operator:*Answer is: 63.0Z:\ACN-II\tcp>java S_oprWaiting for connection...Connection Established....

Page | 19

Page 20: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

7. Write a program to accept a new random number from the server.

/*======================================================================

SERVER CODE======================================================================*/

importjava.util.*;import java.io.*;import java.net.*;

classRandServer{

public static void main(String args[]){

ServerSocketssocket = null;Socket socket = null;PrintWriterpw = null;

try{

ssocket = new ServerSocket(8189);

socket = ssocket.accept();

Random rand = new Random();

pw = new PrintWriter(socket.getOutputStream(),true);

for(inti = 0; i< 5 ; i++){

pw.println("" + rand.nextInt(5));}

}catch(Exception e){

e.printStackTrace();}

Page | 20

Page 21: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

finally{

try{

pw.close();socket.close();

}catch(IOException e){

System.err.println(e);}

}}

}/*======================================================================

CLIENT CODE======================================================================*/

importjava.util.*;import java.io.*;import java.net.*;

classRandClient{

public static void main(String args[]){

Scanner scan = null;Socket socket = null;

try{

socket = new Socket(InetAddress.getLocalHost(),8189);

scan = new Scanner(socket.getInputStream());

intrand;

System.out.println("\nServer Generated Random Numbers : ");

Page | 21

Page 22: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

for(inti = 0 ; i< 5 ;i++){

rand = scan.nextInt();System.out.println("\t" + rand);

}}catch(Exception e){

e.printStackTrace();}finally{

try{

scan.close();socket.close();

}catch(IOException e){

System.err.println(e);}

}}

}

Page | 22

Page 23: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

/*======================================================================OUTPUT:

Z:\KRUPA_sem8\LDCE\ACN\Program-7>javac RandServer.java

Z:\KRUPA_sem8\LDCE\ACN\Program-7>javac RandClient.java

Z:\KRUPA_sem8\LDCE\ACN\Program-7>java RandServer

Z:\KRUPA_sem8\LDCE\ACN\Program-7>java RandClient

Server Generated Random Numbers: 1 0 3 3 2======================================================================*/

Page | 23

Page 24: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

8./9. Write a program which provides an option for the user to go for either an echo server or daytime server and also a client who can choose the server for user specified action.

===============================================================================

SERVER CODE===============================================================================

import java.io.*;import java.net.*;importjava.util.*;

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

try {

inti;ServerSocketss = new ServerSocket(2021);System.out.println("Server Started.... ");Socket s = ss.accept();InputStream is = s.getInputStream();DataInputStreamdis = new DataInputStream(is);DataInputStreamind = new DataInputStream(System.in);BufferedReader in = new BufferedReader(new

InputStreamReader(s.getInputStream()));BufferedWriterbw = new BufferedWriter(new

OutputStreamWriter(s.getOutputStream()));PrintWriter out = new PrintWriter(bw,true);i = dis.readInt();System.out.println("\nChoice : " + i);if(i==1){

try{

String str = in.readLine();System.out.println("\nMessage From Client :");

Page | 24

Page 25: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

System.out.println(str);out.println(str);s.close();

} catch(Exception e){

System.out.println("Exception: " + e);}finally{

System.out.println("\nDisconnected From Client.");

} }

else {

try {

Date todaysdate = new Date();OutputStreamos = s.getOutputStream();DataOutputStreamdos = new

DataOutputStream(os);Date generate = new Date();System.out.println("\nToday's Date : "+generate); s.close();

}catch(Exception e) {

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

} }catch(Exception e) {

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

}}

Page | 25

Page 26: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

===============================================================================

CLIENT CODE===============================================================================import java.io.*;importjava.util.*;import java.net.*;

classEcho_Date_Client{

public static void main(String[] args){

try{

inti;Socket s = new Socket("localhost",2021);DataInputStreamin_data = new

DataInputStream(System.in);BufferedReader in = new BufferedReader( new

InputStreamReader (s.getInputStream()));

BufferedWriterbw = new BufferedWriter(new OutputStreamWriter

(s.getOutputStream()));PrintWriter out = new PrintWriter(bw,true);OutputStreamos = s.getOutputStream();DataOutputStreamdos = new DataOutputStream(os);System.out.println(" ");System.out.println(" 1. Echo Server.");System.out.println(" 2. Date Server.");System.out.println(" ");System.out.print("Enter Your Choice : ");i = Integer.parseInt(in_data.readLine());dos.writeInt(i);if(i==1){

try{

System.out.println("\nEnter Your Message : ");

String message = in_data.readLine();

Page | 26

Page 27: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

out.println(message);String str = in.readLine();System.out.println("\nMessage From

Server : ");System.out.println(str);s.close();

}catch(Exception e){

System.out.println("Exception: " + e);}finally{

System.out.println("\nDisconnected From Server.");

}}else{

try{

InputStream is = s.getInputStream();DataInputStreamdis = new

DataInputStream(is);Date t = new Date();System.out.println("\nToday's Date : "+ t);s.close();

}catch(Exception e){

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

}}catch(Exception e){

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

}}

OUTPUT:

Page | 27

Page 28: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

=====================================================================Z:\KRUPA_sem8\LDCE\ACN\EchoDate>javac *.java

Z:\KRUPA_sem8\LDCE\ACN\EchoDate>java Echo_Date_ServerServer Started....

Choice: 1

Message from Client:Hello to All

Disconnected From Client.

Z:\KRUPA_sem8\LDCE\ACN\EchoDate>java Echo_Date_Client 1. Echo Server. 2. Date Server.

Enter Your Choice: 1

Enter Your Message:Hello to All

Message from Server:Hello to All

Disconnected From Server.=====================================================================

Page | 28

Page 29: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

10. Write a client and a DNS server where given a URL and server sends back an IP address.

===============================================================================

SERVER CODE===============================================================================

import java.io.*;importjava.util.*;import java.net.*;

classDNSServer{

public static void main(String args[]){

boolean flag=true;try{

ServerSocketss= new ServerSocket(2100);System.out.println("DNS Server Started.......");String address="";FileReaderfr=new FileReader("DNS.txt");BufferedReaderbr=new BufferedReader(fr);StreamTokenizerst=new StreamTokenizer(br);st.wordChars('\'', '\'');Socket s=ss.accept();InputStream is= s.getInputStream();DataInputStreamdis= new DataInputStream(is);String urlname=dis.readUTF();while(st.nextToken()!=StreamTokenizer.TT_EOF){

intcnt=0;StringBuffer sb1=new StringBuffer(urlname);sb1.insert(0,'\'');sb1.append('\'');StringBuffer sb2=new StringBuffer(st.sval);inti;for(i=0;i<sb1.length();i++){

Page | 29

Page 30: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

if(sb1.charAt(i) ==sb2.charAt(i)){

flag=true;}else{

flag=false;break;

}}if(flag==true){

st.nextToken();address=st.sval;break;

}else{

address="No Records Found...";}

}

OutputStreamos=s.getOutputStream();DataOutputStreamdos=new DataOutputStream(os);dos.writeUTF(address);s.close();fr.close();

}catch(Exception e){

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

}}

Page | 30

Page 31: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

===============================================================================

CLIENT CODE===============================================================================import java.io.*;importjava.util.*;import java.net.*;

classDNSClient{

public static void main(String args[]){

try{

Socket s = new Socket("localhost",2100);boolean flag;

DataInputStream in = new DataInputStream(System.in);System.out.println("Enter URL Name : ");String name = in.readLine();String urlname = name.toLowerCase();

OutputStreamos=s.getOutputStream();DataOutputStreamdos=new DataOutputStream(os);dos.writeUTF(urlname);InputStream is= s.getInputStream();

DataInputStreamdis=new DataInputStream(is);String physical=dis.readUTF();System.out.println("\nPhysical Address of " + urlname +

": \n" + physical);s.close();

}catch(Exception e){

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

}}

Page | 31

Page 32: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

===============================================================================

DNS.txt File==============================================================================='www.yahoo.com' '21.21.21.21''www.hotmail.com' '192.168.21.2''www.google.co.in' '192.21.21.21''www.cert.org' '192.168.21.21'

OUTPUT:=====================================================================Z:\KRUPA_sem8\LDCE\ACN\DNS>javac *.java

Z:\KRUPA_sem8\LDCE\ACN\DNS>java DNSServerDNS Server Started.......

Z:\KRUPA_sem8\LDCE\ACN\DNS>java DNSClientEnter URL Name:www.yahoo.com

Physical Address of www.yahoo.com:'21.21.21.21'

Page | 32

Page 33: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

11. Use threading in DNS server that have designed to allow multiple users at the same time.

===============================================================================

SERVER CODE===============================================================================

import java.io.*;importjava.util.*;import java.net.*;

public class MultiDNSServer{

public static void main(String args[]){

try{

ServerSocketss = new ServerSocket(2100);System.out.println("DNSServer Started.......");while(true){

Socket s = ss.accept();newDNSServer(s);

}}catch(Exception e){

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

}}classDNSServer extends Thread{

Socket s;FileReaderfr;BufferedReaderbr;StreamTokenizerst;InputStream is;DataInputStreamdis;OutputStreamos;

Page | 33

Page 34: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

DataOutputStreamdos;publicDNSServer(Socket s){

this.s = s;try{

fr=new FileReader("DNS.txt");br=new BufferedReader(fr);st=new StreamTokenizer(br);is= s.getInputStream();dis= new DataInputStream(is);os=s.getOutputStream();dos=new DataOutputStream(os);start();

}catch(Exception e){

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

}public void run(){

boolean flag=true;try{

String address="";st.wordChars('\'', '\'');InputStream is= s.getInputStream();DataInputStreamdis= new DataInputStream(is);String urlname=dis.readUTF();while(st.nextToken()!=StreamTokenizer.TT_EOF){

intcnt=0,i;StringBuffer sb1=new StringBuffer(urlname);sb1.insert(0,'\'');sb1.append('\'');StringBuffer sb2=new StringBuffer(st.sval);for(i=0;i<sb1.length();i++){

if(sb1.charAt(i) ==sb2.charAt(i)){

flag=true;

Page | 34

Page 35: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

}else{

flag=false;break;

}}if(flag==true){

st.nextToken();address=st.sval;break;

}else{

address="No Records Found...";}

}dos.writeUTF(address);

}catch(Exception e){

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

}}

Page | 35

Page 36: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

===============================================================================

CLIENT CODE===============================================================================import java.io.*;importjava.util.*;import java.net.*;

classMultiDNSClient{

public static void main(String args[]){

try{

Socket s = new Socket("localhost",2100);boolean flag;DataInputStream in = new DataInputStream(System.in);System.out.println("Enter URL Name : ");String name = in.readLine();String urlname = name.toLowerCase();OutputStreamos=s.getOutputStream();DataOutputStreamdos=new DataOutputStream(os);dos.writeUTF(urlname);InputStream is= s.getInputStream();DataInputStreamdis=new DataInputStream(is);String physical=dis.readUTF();System.out.println("\nPhysical Address of " + urlname +

": \n" + physical);

s.close();}catch(Exception e){

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

}}

Page | 36

Page 37: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

OUTPUT:=====================================================================Z:\KRUPA_sem8\LDCE\ACN\MultiDNS>javac *.java

Z:\KRUPA_sem8\LDCE\ACN\MultiDNS>java MultiDNSServerDNSServer Started.......Exception: java.io.FileNotFoundException: DNS.txt (The system cannot find the file specified)

Z:\KRUPA_sem8\LDCE\ACN\MultiDNS>java MultiDNSClient

Enter URL Name:www.google.com

Physical Address of www.google.com:No Records Found...

Z:\KRUPA_sem8\LDCE\ACN\MultiDNS>java MultiDNSClientEnter URL Name:www.google.co.in

Physical Address of www.google.co.in:'192.21.21.21'

Page | 37

Page 38: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

12. Write a program for broadcast messages from server to all the client.===============================================================================

SERVER CODE===============================================================================

import java.net.*;import java.io.*;importjava.util.*;

public class Server_Broadcast{

static String msg = "";public static void main(String args[]) throws IOException{

ServerSocket s = new ServerSocket(2100);System.out.println("Server Started .....");acceptthread at = new acceptthread(s);InputStreamReader in = new InputStreamReader(System.in);BufferedReaderbr = new BufferedReader(in);while(!msg.equals("exit")){

System.out.println("Enter Your Message : ");msg = br.readLine();at.notifyAllUsers();

}s.close();System.exit(0);

}}

classacceptthread extends Thread{

ServerSocket sock;boolean t = true;staticint connections=1;ArrayListarl = new ArrayList();publicacceptthread(ServerSocket s){

Page | 38

Page 39: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

sock = s;start();

}public void run(){

while(t){

try{

Socket skt = sock.accept();writethreadwt = new writethread(skt);arl.add(wt);

}catch(Exception e) {

System.out.println("Exception : " + e);}if(t == false) break;

}}public void notifyAllUsers(){

for(int j=0;j<arl.size();j++){

writethreadww = (writethread)arl.get(j);synchronized(ww){

ww.notify();}

}}

}

classwritethread extends Thread{

Socket soc;writethread(Socket s){

soc = s;start();

}synchronized public void run()

Page | 39

Page 40: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

{try{

OutputStreamos = soc.getOutputStream();DataOutputStreamdout = new DataOutputStream(os);while(!Server_Broadcast.msg.equals("exit")){

try{wait();}catch(Exception e){

System.out.println("Exception : " + e);}dout.writeUTF(Server_Broadcast.msg);

}dout.close();os.close();soc.close();

}catch(Exception e){

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

}}

===============================================================================

CLIENT CODE===============================================================================

import java.io.*;import java.net.*;importjava.util.*;

public class Client_Broadcast{

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

Page | 40

Page 41: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

Socket s = new Socket("localhost",2100);InputStream is = s.getInputStream();DataInputStreamdis = new DataInputStream(is);String msg1 = "";while(!msg1.equals("exit")){

try{

msg1 = dis.readUTF();System.out.println("Message From Server : " +

msg1);}catch(Exception e){

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

}dis.close();is.close();s.close();

}}

OUTPUT:=====================================================================Z:\KRUPA_sem8\LDCE\ACN\Broadcast>javac *.java

Z:\KRUPA_sem8\LDCE\ACN\Broadcast>java Server_Broadcast

Server Started.....Enter Your Message:Hello

Enter Your Message:You all are Welcome to the CTI

Z:\KRUPA_sem8\LDCE\ACN\Broadcast>java Client_Broadcast

Message from Server: HelloMessage from Server: You all are Welcome to the CTI

Page | 41

Page 42: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

13. Write a program for broadcast messages from a client to multiple clients through server.

===============================================================================

SERVER CODE===============================================================================

import java.net.*;import java.io.*;importjava.util.*;

public class Server_Broadcast{

static String msg = "";public static void main(String args[]) throws IOException{

ServerSocket s = new ServerSocket(2100);System.out.println("Server Started .....");acceptthread at = new acceptthread(s);InputStreamReader in = new InputStreamReader(System.in);BufferedReaderbr = new BufferedReader(in);while(!msg.equals("exit")){

System.out.println("Enter Your Message : ");msg = br.readLine();at.notifyAllUsers();

}s.close();System.exit(0);

}}

classacceptthread extends Thread{

ServerSocket sock;boolean t = true;staticint connections=1;ArrayListarl = new ArrayList();publicacceptthread(ServerSocket s)

Page | 42

Page 43: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

{sock = s;start();

}public void run(){

while(t){

try{

Socket skt = sock.accept();writethreadwt = new writethread(skt);arl.add(wt);

}catch(Exception e) {

System.out.println("Exception : " + e);}if(t == false) break;

}}public void notifyAllUsers(){

for(int j=0;j<arl.size();j++){

writethreadww = (writethread)arl.get(j);synchronized(ww){

ww.notify();}

}}

}

classwritethread extends Thread{

Socket soc;writethread(Socket s){

soc = s;start();

}

Page | 43

Page 44: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

synchronized public void run(){

try{

OutputStreamos = soc.getOutputStream();DataOutputStreamdout = new DataOutputStream(os);while(!Server_Broadcast.msg.equals("exit")){

try{wait();}catch(Exception e){

System.out.println("Exception : " + e);}dout.writeUTF(Server_Broadcast.msg);

}dout.close();os.close();soc.close();

}catch(Exception e){

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

}}

===============================================================================

CLIENT CODE===============================================================================

import java.io.*;import java.net.*;importjava.util.*;

public class Client_Broadcast{

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

Page | 44

Page 45: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

{Socket s = new Socket("localhost",2100);InputStream is = s.getInputStream();DataInputStreamdis = new DataInputStream(is);String msg1 = "";while(!msg1.equals("exit")){

try{

msg1 = dis.readUTF();System.out.println("Message From Server : " +

msg1);}catch(Exception e){

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

}dis.close();is.close();s.close();

}}

OUTPUT:=====================================================================Z:\KRUPA_sem8\LDCE\ACN\Broadcast>javac *.java

Z:\KRUPA_sem8\LDCE\ACN\Broadcast>java Server_Broadcast

Server Started.....Enter Your Message:Hello

Enter Your Message:You all are Welcome to the CTI

Z:\KRUPA_sem8\LDCE\ACN\Broadcast>java Client_Broadcast

Message from Server: HelloMessage from Server: You all are Welcome to the CTI

Page | 45

Page 46: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

14. Write a chat server and client to chat between any two clients.

// Chat Server runs at port no. 9999import java.io.*;importjava.util.*;import java.net.*;import static java.lang.System.out;

public class ChatServer { Vector<String> users = new Vector<String>(); Vector<HandleClient> clients = new Vector<HandleClient>();

public void process() throws Exception {ServerSocket server = new ServerSocket(9999,10);out.println("Server Started...");while( true) {

Socket client = server.accept();HandleClient c = new HandleClient(client);clients.add(c);

} // end of while }public static void main(String ... args) throws Exception {newChatServer().process(); } // end of main

public void boradcast(String user, String message) { // send message to all connected usersfor ( HandleClient c : clients )if ( ! c.getUserName().equals(user) )c.sendMessage(user,message);

}

class HandleClient extends Thread { String name = "";

BufferedReader input;PrintWriter output;

publicHandleClient(Socket client) throws Exception { // get input and output streams

Page | 46

Page 47: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

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

output = new PrintWriter ( client.getOutputStream(),true); // read namename =input.readLine();users.add(name); // add to vectorstart();

}

public void sendMessage(String uname,Stringmsg) {output.println(uname + ":" + msg);}

public String getUserName() { return name; }public void run() {

String line;try {

while(true) {line = input.readLine();if ( line.equals("end") ) {clients.remove(this);users.remove(name);break;

}boradcast(name,line); // method of outer class - send

messages to all } // end of while } // trycatch(Exception ex) {System.out.println(ex.getMessage()); }

} // end of run() } // end of inner class

} // end of Server

Page | 47

Page 48: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

Client:-

import java.io.*;importjava.util.*;import java.net.*;importjavax.swing.*;importjava.awt.*;importjava.awt.event.*;import static java.lang.System.out;

public class ChatClient extends JFrame implements ActionListener { String uname;PrintWriterpw;BufferedReaderbr;JTextAreataMessages;JTextFieldtfInput;JButtonbtnSend,btnExit; Socket client;

publicChatClient(String uname,Stringservername) throws Exception {super(uname); // set title for framethis.uname = uname;client = new Socket(servername,9999);br = new BufferedReader( new InputStreamReader( client.getInputStream()) ) ;pw = new PrintWriter(client.getOutputStream(),true);pw.println(uname); // send name to serverbuildInterface();newMessagesThread().start(); // create thread for listening for messages }

public void buildInterface() {btnSend = new JButton("Send");btnExit = new JButton("Exit");taMessages = new JTextArea();taMessages.setRows(10);taMessages.setColumns(50);taMessages.setEditable(false);tfInput = new JTextField(50);

Page | 48

Page 49: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

JScrollPanesp = new JScrollPane(taMessages, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);add(sp,"Center");JPanelbp = new JPanel( new FlowLayout());bp.add(tfInput);bp.add(btnSend);bp.add(btnExit);add(bp,"South");btnSend.addActionListener(this);btnExit.addActionListener(this);setSize(500,300);setVisible(true);pack(); }

public void actionPerformed(ActionEventevt) {if ( evt.getSource() == btnExit ) {pw.println("end"); // send end to server so that server know about the terminationSystem.exit(0); } else { // send message to serverpw.println(tfInput.getText()); } }

public static void main(String ... args) {

// take username from user String name = JOptionPane.showInputDialog(null,"Enter your name :", "Username",JOptionPane.PLAIN_MESSAGE); String servername = "localhost"; try {newChatClient( name ,servername); } catch(Exception ex) {out.println( "Error --> " + ex.getMessage()); }

} // end of main

Page | 49

Page 50: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

// inner class for Messages Threadclass MessagesThread extends Thread {public void run() { String line;try {while(true) {line = br.readLine();taMessages.append(line + "\n"); } // end of while } catch(Exception ex) {} } }} // end of client

Page | 50

Page 51: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

15. Write a simple HTTP type client and server, when given URL sends back the page.

HTTP 1.1 Clients

To comply with HTTP 1.1, clients must

include the   Host:   header with each request accept responses with   chunked   data either support   persistent connections , or include the

" Connection:   close " header with each request handle the " 100   Continue " response

Host: Header

Starting with HTTP 1.1, one server at one IP address can be multi-homed, i.e. the home of several Web domains. For example, "www.host1.com" and "www.host2.com" can live on the same server.

Several domains living on the same server is like several people sharing one phone: a caller knows who they're calling for, but whoever answers the phone doesn't. Thus, every HTTP request must specify which host name (and possibly port) the request is intended for, with the Host: header. A complete HTTP 1.1 request might be

GET /path/file.html HTTP/1.1Host: www.host1.com:80[blank line here]

except the ":80" isn't required, since that's the default HTTP port.

Host: is the only required header in an HTTP 1.1 request. It's also the most urgently needed new feature in HTTP 1.1. Without it, each host name requires a unique IP address, and we're quickly running out of IP addresses with the explosion of new domains.

Chunked Transfer-Encoding

If a server wants to start sending a response before knowing its total length (like with long script output), it might use the simple chunked transfer-encoding, which breaks the complete response into smaller chunks and sends them in series. You can identify such a response because it contains the "Transfer-Encoding: chunked" header. All HTTP 1.1 clients must be able to receive chunked messages.

Page | 51

Page 52: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

A chunked message body contains a series of chunks, followed by a line with "0" (zero), followed by optional footers (just like headers), and a blank line. Each chunk consists of two parts:

a line with the size of the chunk data, in hex, possibly followed by a semicolon and extra parameters you can ignore (none are currently standard), and ending with CRLF.

the data itself, followed by CRLF.

So a chunked response might look like the following:

HTTP/1.1 200 OKDate: Fri, 31 Dec 1999 23:59:59 GMTContent-Type: text/plainTransfer-Encoding: chunked

1a; ignore-stuff-hereabcdefghijklmnopqrstuvwxyz101234567890abcdef0some-footer: some-valueanother-footer: another-value[blank line here]

Note the blank line after the last footer. The length of the text data is 42 bytes (1a + 10, in hex), and the data itself is abcdefghijklmnopqrstuvwxyz1234567890abcdef. The footers should be treated like headers, as if they were at the top of the response.

The chunks can contain any binary data, and may be much larger than the examples here. The size-line parameters are rarely used, but you should at least ignore them correctly. Footers are also rare, but might be appropriate for things like checksums or digital signatures.

For comparison, here's the equivalent to the above response, without using chunked encoding:

HTTP/1.1 200 OKDate: Fri, 31 Dec 1999 23:59:59 GMTContent-Type: text/plainContent-Length: 42some-footer: some-value

Page | 52

Page 53: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

another-footer: another-value

abcdefghijklmnopqrstuvwxyz1234567890abcdef

Persistent Connections and the "Connection: close" Header

In HTTP 1.0 and before, TCP connections are closed after each request and response, so each resource to be retrieved requires its own connection. Opening and closing TCP connections takes a substantial amount of CPU time, bandwidth, and memory. In practice, most Web pages consist of several files on the same server, so much can be saved by allowing several requests and responses to be sent through a single persistent connection.

Persistent connections are the default in HTTP 1.1, so nothing special is required to use them. Just open a connection and send several requests in series (called pipelining), and read the responses in the same order as the requests were sent. If you do this, be very careful to read the correct length of each response, to separate them correctly.

If a client includes the "Connection: close" header in the request, then the connection will be closed after the corresponding response. Use this if you don't support persistent connections, or if you know a request will be the last on its connection. Similarly, if a response contains this header, then the server will close the connection following that response, and the client shouldn't send any more requests through that connection.

A server might close the connection before all responses are sent, so a client must keep track of requests and resend them as needed. When resending, don't pipeline the requests until you know the connection is persistent. Don't pipeline at all if you know the server won't support persistent connections (like if it uses HTTP 1.0, based on a previous response).

The "100 Continue" Response

During the course of an HTTP 1.1 client sending a request to a server, the server might respond with an interim "100 Continue" response. This means the server has received the first part of the request, and can be used to aid communication over slow links. In any case, all HTTP 1.1 clients must handle the 100 response correctly (perhaps by just ignoring it).

Page | 53

Page 54: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

The "100 Continue" response is structured like any HTTP response, i.e. consists of a status line, optional headers, and a blank line. Unlike other responses, it is always followed by another complete, final response.

So, further extending the last example, the full data that comes back from the server might consist of two responses in series, like

HTTP/1.1 100 Continue

HTTP/1.1 200 OKDate: Fri, 31 Dec 1999 23:59:59 GMTContent-Type: text/plainContent-Length: 42some-footer: some-valueanother-footer: another-value

abcdefghijklmnoprstuvwxyz1234567890abcdef

To handle this, a simple HTTP 1.1 client might read one response from the socket; if the status code is 100, discard the first response and read the next one instead.

HTTP 1.1 Servers

To comply with HTTP 1.1, servers must:

require the   Host:   header from HTTP   1.1 clients accept absolute URL's in a request accept requests with   chunked   data either support   persistent connections , or include the

" Connection:   close " header with each response use the " 100   Continue " response appropriately include the   Date:   header in each response handle requests with   If-Modified-Since:   or   If-Unmodified-

Since:   headers support at least the GET and HEAD methods support HTTP   1.0 requests

Requiring the Host: Header

Page | 54

Page 55: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

Because of the urgency of implementing the new Host: header, servers are not allowed to tolerate HTTP 1.1 requests without it. If a server receives such a request, it must return a "400 Bad Request" response, like

HTTP/1.1 400 Bad RequestContent-Type: text/htmlContent-Length: 111

<html><body><h2>No Host: header received</h2>HTTP 1.1 requests must include the Host: header.</body></html>

This requirement applies only to clients using HTTP 1.1, not any future version of HTTP. If the request uses an HTTP version later than 1.1, the server can accept an absolute URL instead of a Host: header (see next section). If the request uses HTTP 1.0, the server may accept the request without any host identification.

Accepting Absolute URL's

The Host: header is actually an interim solution to the problem of host identification. In future versions of HTTP, requests will use an absolute URL instead of a pathname, like

GET http://www.somehost.com/path/file.html HTTP/1.2

To enable this protocol transition, HTTP 1.1 servers must accept this form of request, even though HTTP 1.1 clients won't send them. The server must still report an error if an HTTP 1.1 client leaves out the Host: header, as described in the previous section.

Chunked Transfer-Encoding

Just as HTTP 1.1 clients must accept chunked responses, servers must accept chunked requests (an unlikely scenario, but possible). See the earlier section on HTTP   1.1 Clients  for details of the chunked data format.

Servers aren't required to generate chunked messages; they just have to be able to receive them.

Persistent Connections and the "Connection: close" Header

Page | 55

Page 56: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

If an HTTP 1.1 client sends multiple requests through a single connection, the server should send responses back in the same order as the requests-- this is all it takes for a server to support persistent connections.

If a request includes the "Connection: close" header, that request is the final one for the connection and the server should close the connection after sending the response. Also, the server should close an idle connection after some timeout period (can be anything; 10 seconds is fine).

If you don't want to support persistent connections, include the "Connection: close" header in the response. Use this header whenever you want to close the connection, even if not all requests have been fulfilled. The header says that the connection will be closed after the current response, and a valid HTTP 1.1 client will handle it correctly.

Using the "100 Continue" Response

As described in the section on HTTP   1.1 Clients , this response exists to help deal with slow links.

When an HTTP 1.1 server receives the first line of an HTTP 1.1 (or later) request, it must respond with either "100 Continue" or an error. If it sends the "100 Continue" response, it must also send another, final response, once the request has been processed. The "100 Continue" response requires no headers, but must be followed by the usual blank line, like:

HTTP/1.1 100 Continue[blank line here][another HTTP response will go here]

Don't send "100 Continue" to HTTP 1.0 clients, since they don't know how to handle it.

The Date: Header

Caching is an important improvement in HTTP 1.1, and can't work without timestamped responses. So, servers must timestamp every response with a Date: header containing the current time, in the form

Date: Fri, 31 Dec 1999 23:59:59 GMT

Page | 56

Page 57: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

All responses except those with 100-level status (but including error responses) must include the Date: header.

All time values in HTTP use Greenwich Mean Time.

Handling Requests with If-Modified-Since: or If-Unmodified-Since: Headers

To avoid sending resources that don't need to be sent, thus saving bandwidth, HTTP 1.1 defines the If-Modified-Since: and If-Unmodified-Since: request headers. The former says "only send the resource if it has changed since this date"; the latter says the opposite. Clients aren't required to use them, but HTTP 1.1 servers are required to honor requests that do use them.

Unfortunately, due to earlier HTTP versions, the date value may be in any of three possible formats:

If-Modified-Since: Fri, 31 Dec 1999 23:59:59 GMTIf-Modified-Since: Friday, 31-Dec-99 23:59:59 GMTIf-Modified-Since: Fri Dec 31 23:59:59 1999

Again, all time values in HTTP use Greenwich Mean Time (though try to be tolerant of non-GMT times). If a date with a two-digit year seems to be more than 50 years in the future, treat it as being in the past-- this helps with the millennium bug. In fact, do this with any date handling in HTTP 1.1.

Although servers must accept all three date formats, HTTP 1.1 clients and servers must only generate the first kind.

If the date in either of these headers is invalid, or is in the future, ignore the header.

If, without the header, the request would result in an unsuccessful (non-200-level) status code, ignore the header and send the non-200-level response. In other words, only apply these headers when you know the resource would otherwise be sent.

The If-Modified-Since: header is used with a GET request. If the requested resource has been modified since the given date, ignore the header and return the resource as you normally would. Otherwise, return a "304 Not Modified" response, including the Date: header and no message body, like

Page | 57

Page 58: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

HTTP/1.1 304 Not ModifiedDate: Fri, 31 Dec 1999 23:59:59 GMT[blank line here]

The If-Unmodified-Since: header is similar, but can be used with any method. If the requested resource has not been modified since the given date, ignore the header and return the resource as you normally would. Otherwise, return a "412 Precondition Failed" response, like

HTTP/1.1 412 Precondition Failed[blank line here]

Supporting the GET and HEAD methods

To comply with HTTP 1.1, a server must support at least the GET and HEAD methods. If you're handling CGI scripts, you should probably support the POST method too.

Four other methods (PUT, DELETE, OPTIONS, and TRACE) are defined in HTTP 1.1, but are rarely used. If a client requests a method you don't support, respond with "501 Not Implemented", like

HTTP/1.1 501 Not Implemented[blank line here]

Supporting HTTP 1.0 Requests

To be compatible with older browsers, HTTP 1.1 servers must support HTTP 1.0 requests. In particular, when a request uses HTTP 1.0 (as identified in the initial request line),

don't require the Host: header, and don't send the "100 Continue" response.

Page | 58

Page 59: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

16. Write a simple FTP client and server which let the user pass the file to and from.

prevost:~> ftp

ftp> debug

Debugging on (debug=1).

ftp> open 127.0.0.1 6161

Connected to 127.0.0.1.

220 Ready to execute commands

Name (127.0.0.1:a1a1): joeluser

---> USER joeluser

530 Not logged in

Login failed.

ftp> user anonymous

---> USER anonymous

230 User logged in, proceed

ftp> cd cs219/Labs/Threads

---> CWD cs219/Labs/Threads

250 The current directory has been changed to /tmp/cs219/Labs/Threads

ftp>ls

---> PORT 127,0,0,1,146,41

200 Port command okay.

---> NLST

125 Transfer starting

SocketEmail.tar.gz

Page | 59

Page 60: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

oldFtpStuff

226 Requested file action successful

23 bytes received in 0.11 seconds (0.20 Kbytes/s)

ftp> get SocketEmail.tar.gz

---> PORT 127,0,0,1,146,50

200 Port command okay.

---> RETR SocketEmail.tar.gz

125 Data connection already open; transfer starting

250 Requested file action okay, completed

local: SocketEmail.tar.gz remote: SocketEmail.tar.gz

1869 bytes received in 0.1 seconds (17.99 Kbytes/s)

ftp> cd ..

--->CWD ..

250 The current directory has been changed to /tmp/cs219/Labs

ftp> cd ..

--->CWD ..

250 The current directory has been changed to /tmp/cs219

ftp>ls

---> PORT 127,0,0,1,146,53

200 Port command okay.

---> NLST

125 Transfer starting

Labs

old.tar.gz

Page | 60

Page 61: ACN Practicals

100280116026 8TH I.T(A) L.D College Of Engineering

Summer2002.tar.gz

timesheet.txt

226 Requested file action successful

48 bytes received in 0.11 seconds (0.44 Kbytes/s)

ftp> quit

---> QUIT

221 Logging out

Page | 61