26
K.S.R. COLLEGE OF ENGINEERING TIRUCHENGODE-637 215 ANNA UNIVERSITY: COIMBATORE (REGULATION: 2008) 1

Lab Manual CN(Odd Sem)

Embed Size (px)

Citation preview

Page 1: Lab Manual CN(Odd Sem)

K.S.R. COLLEGE OF ENGINEERING

TIRUCHENGODE-637 215

ANNA UNIVERSITY: COIMBATORE

(REGULATION: 2008)

(FOR III YEAR B.E CSE, FIFTH SEMESTER)

STAFF INCHARGE HOD

1

Page 2: Lab Manual CN(Odd Sem)

COMPUTER NETWORKS LAB

LIST OF PROGRAMS

S.no Name of the Program Page no1 Socket programming

2 Data grams

3 TCP

4 SMTP

5 FTP

6 Implementation of any two congestion control algorithms

2

Page 3: Lab Manual CN(Odd Sem)

SOCKET PROGRAMMING

Ex. No 1 Program for Echo Client and Echo Server

AimTo write a program in c/ java to implement echo client and echo server.

Algorithm1. Start2. Create necessary input and output streams3. Create a socket connection from client to the server with corresponding IP

address and port number4. Get any string from the client side console5. Pass this string to the server which echoes back to the client6. Read the same string from the client side socket’s input stream.7. Display the output string that is echoed back to the client.

ProgramClient //echoclient.javaimport java.io.*;import java.net.*;public class echoclient{public static void main(String args[]){try{Socket s=new Socket("localhost",9999);BufferedReader r = new BufferedReader(new InputStreamReader(s.getInputStream()));PrintWriter w=new PrintWriter(s.getOutputStream(),true);BufferedReader con = new BufferedReader (new InputStreamReader(System.in));String line,rline;do{line=con.readLine();if(line!=null){

w.println(line);}

3

Page 4: Lab Manual CN(Odd Sem)

rline=r.readLine();System.out.println("Echo from server"+rline);}while(!line.trim().equals("bye"));}catch(Exception err){ System.out.println("error"+err);}}}Server

// echoServer.javaimport java.io.*;import java.net.*;public class echoServer{ public static void main (String args[]) { try { ServerSocket ser = new ServerSocket(9999); while(true) { Socket client = ser.accept(); BufferedReader r=new BufferedReader(new InputStreamReader(client.getInputStream())); PrintWriter w=new PrintWriter(client.getOutputStream(),true); System.out.println("Welcome to java echoserver"); String line; do { line =r.readLine (); if(line!=null) w.println("SERVER:"+line); System.out.println (line); } while (! line.trim().equals("bye")); if(line.equals("bye")) System.exit(0); client.close(); }

}catch(Exception err){System.out.println("Error:"+err);

4

Page 5: Lab Manual CN(Odd Sem)

}}}

Output

5

Page 6: Lab Manual CN(Odd Sem)

RESULTThus a program is written to implement the echo client and echo server

Ex. No 2 Program to Implement DNS using UDP

AimTo Write a program to implement the Domain Name System using UDP

Algorithm1. Start2. Declare the necessary variables for the predefined structures hostent and

utsname3. Get the hostname from the user through console4. get the ip address of the hostname using the function gethostbyname()5. Display the ip address corresponding to the hostname.6. Stop

Program// Print out DNS Record for an Internet Addressimport javax.naming.directory.Attributes;import javax.naming.directory.InitialDirContext;import javax.naming.NamingEnumeration;import javax.naming.NamingException;import java.net.InetAddress;import java.net.UnknownHostException;

public class DNSLookup{ public static void main(String args[]) { // explain what program does and how to use it if (args.length != 1) { System.err.println("Print out DNS Record for an Internet Address"); System.err.println("USAGE: java DNSLookup domainName|domainAddress"); System.exit(-1); } try { InetAddress inetAddress; // if first character is a digit then assume is an address if (Character.isDigit(args[0].charAt(0))) { // convert address from string representation to byte array byte[] b = new byte[4]; String[] bytes = args[0].split("[.]");

6

Page 7: Lab Manual CN(Odd Sem)

for (int i = 0; i < bytes.length; i++) { b[i] = new Integer(bytes[i]).byteValue(); } // get Internet Address of this host address inetAddress = InetAddress.getByAddress(b); } else { // get Internet Address of this host name inetAddress = InetAddress.getByName(args[0]); } // show the Internet Address as name/address System.out.println(inetAddress.getHostName() + "/" + inetAddress.getHostAddress()); // get the default initial Directory Context InitialDirContext iDirC = new InitialDirContext(); // get the DNS records for inetAddress Attributes attributes = iDirC.getAttributes("dns:/" + inetAddress.getHostName()); // get an enumeration of the attributes and print them out NamingEnumeration attributeEnumeration = attributes.getAll(); System.out.println("-- DNS INFORMATION --"); while (attributeEnumeration.hasMore()) { System.out.println("" + attributeEnumeration.next()); } attributeEnumeration.close(); } catch (UnknownHostException exception) { System.err.println("ERROR: No Internet Address for '" + args[0] + "'"); } catch (NamingException exception) { System.err.println("ERROR: No DNS record for '" + args[0] + "'"); } }}

Output

7

Page 8: Lab Manual CN(Odd Sem)

ResultThus a program is written to implement the Domain Name System.

Ex. No 3 TCP programs

a. Program to Implement Chatting Application

AimTo Write a C++ program to prepare Students Report using Simple Class

with primitive and array data types

Algorithm1. Start2. Create necessary input and output streams3. Create a socket connection from user1 to the user2 with corresponding IP

address and port number4. Get any string from the user1 side console5. Pass this string to the user2 which prints in the console of user26. Read some other string from the user2 side socket’s input stream.7. Pass this string to the user1 which prints in the console of user18. Repeat the same until “exit” command9. Stop

ProgramUser1import java.io.*;import java.net.*;class user1{

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

String sentence, newsentence;DataInputStream in=new DataInputStream(System.in);Socket cs=new Socket("10.1.1.204",6789);

DataInputStream inp=new DataInputStream(cs.getInputStream());DataOutputStream out=new DataOutputStream(cs.getOutputStream());

do{

System.out.print("User1:");sentence=in.readLine();if(sentence.compareTo("exit")!=0){

out.writeBytes(sentence+'\n');newsentence=inp.readLine();System.out.println("User2:"+newsentence);

}

8

Page 9: Lab Manual CN(Odd Sem)

}while(sentence.compareTo("exit")!=0);cs.close();

} }User 2import java.io.*;import java.net.*;class user2{

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

String sentence, newsentence;DataInputStream in=new DataInputStream(System.in);ServerSocket ss=new ServerSocket(6789);Socket s=ss.accept();

DataInputStream inp=new DataInputStream(s.getInputStream());DataOutputStream out=new DataOutputStream(s.getOutputStream());

do{

sentence=inp.readLine();if(sentence.compareTo("exit")!=0){

System.out.println("User1:"+sentence);System.out.print("User2:");newsentence=in.readLine();out.writeBytes(newsentence+'\n');

}}while(sentence.compareTo("exit")!=0);

} }

Output

9

Page 10: Lab Manual CN(Odd Sem)

RESULTThus a program is written to implement the chatting application using TCP

sockets.b. Program to Implement Concurrent Server

AimTo Write a program to implement the concept of concurrent server.

Algorithm1. Start2. Create the necessary sockets in the client and server side systems3. Initialize a thread in the server side system using runnable interface4. Accept the connection requisition from the client side systems inside the

thread.5. Initialize necessary input and output streams for the accepted connection

inside the thread.6. Run any number of clients in parallel communicating the same server.7. The server will respond all the clients at the same time8. Stop

Program

Client 1/ Client 2 / any clientsimport java.io.*;import java.net.*;class Clientcon{

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

String sentence, newsentence,newsentence1;DataInputStream in=new DataInputStream(System.in);

Socket cs=new Socket("pgcse220",6789);DataInputStream inp=new DataInputStream(cs.getInputStream());DataOutputStream out=new DataOutputStream(cs.getOutputStream());

sentence=inp.readLine();System.out.println(sentence);newsentence=in.readLine();out.writeBytes(newsentence+'\n');newsentence1=inp.readLine();System.out.println("From Server:"+newsentence1);cs.close();

}}

Serverimport java.io.*;

10

Page 11: Lab Manual CN(Odd Sem)

import java.net.*;

class Server{

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

int count=0;Thread t= Thread.currentThread();ServerSocket ss=new ServerSocket(6789);while(true){try{

Socket s=ss.accept();count++;conserver c =new conserver(s, count);

}catch(Exception e) {}}

}}

class conserver implements Runnable{

Thread t;Socket s;int c;conserver(Socket s1,int count){

t=new Thread(this, "Demo");t.start();s=s1;c=count;

}public void run(){

try{

DataInputStream inp=new DataInputStream(s.getInputStream());DataOutputStream out=new DataOutputStream(s.getOutputStream());

String sentence="Enter the String:";String newsentence;out.writeBytes(sentence+'\n');newsentence=inp.readLine();

11

Page 12: Lab Manual CN(Odd Sem)

//Thread.sleep(10000);System.out.println("From Client"+c+":"+newsentence);out.writeBytes(newsentence+'\n');

}catch(Exception e) {}

}}

Output

ResultThus a program is written to implement the concurrent server

12

Page 13: Lab Manual CN(Odd Sem)

Ex. No 4 Program for simple mail transfer protocol

AimTo Write a program to implement the concept of SMTP server.

Algorithm

PROGRAM

//SMTP Server

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

class smtpServer{ public static void main (String args[]) throws Exception { ServerSocket ss = new ServerSocket(8080); Socket s = ss.accept(); ServiceClient(s); }

public static void ServiceClient (Socket s) throws Exception { DataInputStream dis = null ; PrintStream ps = null ;

13

Page 14: Lab Manual CN(Odd Sem)

dis = new DataInputStream (s.getInputStream()) ; ps = new PrintStream (s.getOutputStream()); FileWriter f = new FileWriter ("TestMail.eml") ; String tel=dis.readLine(); if(tel.equals("Ready")) System.out.println ("Ready signal Received from client") ;

ps.println("Enter the From address:"); String from = dis.readLine() ; f.write("From:" +from+ "\n") ;

ps.println("Enter the To address:"); String to = dis.readLine(); f.write("To:" + to + "\n");

ps.println("Enter the Subject:"); String sub = dis.readLine(); f.write("Subject:" + sub + "\n"); ps.println("Enter the Message:"); String msg = dis.readLine(); f.write("\nMessage: " + msg + "\n" ) ; f.close(); }}

// SMTP Client

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

class smtpClient{ public static void main (String args[]) throws Exception { Socket s=new Socket("localhost",8080);

DataInputStream dis = new DataInputStream(s.getInputStream()); DataInputStream in = new DataInputStream(System.in); PrintStream ps = new PrintStream(s.getOutputStream());

ps.println("Ready");

System.out.println (dis.readLine()); String strFrom=in.readLine(); ps.println(strFrom);

14

Page 15: Lab Manual CN(Odd Sem)

System.out.println (dis.readLine()); String strTo=in.readLine(); ps.println(strTo);

System.out.println (dis.readLine()); String strSub=in.readLine(); ps.println(strSub);

System.out.println (dis.readLine());

while(true) { String msg=in.readLine(); ps.println(msg);

if(msg.equals("Quit")) { System.out.println

("Message is delivered to server and client quits"); break; } } }}

OUTPUT

Z:\Programs\SMTP>javac smtpServer.javaZ:\Programs\SMTP>javac smtpClient.java

Z:\Programs\SMTP>java smtpServer

Ready signal Received from client

Z:\Programs\SMTP>

Z:\Programs\SMTP>java smtpClient

Enter the From address:[email protected] the To address:[email protected] the Subject:

15

Page 16: Lab Manual CN(Odd Sem)

Test MailEnter the Message:Hello, this mail is generated as part of the SMTP program testing!QuitMessage is delivered to server and client quits

Z:\Programs\SMTP>

// Generated Mail

Result

16

Page 17: Lab Manual CN(Odd Sem)

Thus a program is written to implement the SMTP client and SMTP server

Ex. No 5 Program to Implement File Transfer

AimTo write a program in c/ java to implement file transfer between client and

file server.

Algorithm1. Start2. Create necessary input and output streams3. Create a socket connection from client to the server with corresponding IP

address and port number4. Create necessary file streams5. Get the option from the user to UPLOAD/ DOWNLOAD and the file name

to be transferred6. If UPLOAD, read each byte from the file in the client side and write it into

the output stream of the socket7. In the server side, read the bytes from the input stream and write it into the

file

ProgramClientimport java.io.*;import java.net.*;class user{

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

long end;String fname,f1name;int size=0;String option;DataInputStream in=new DataInputStream(System.in);Socket cs=new Socket("10.1.1.204",6789);DataInputStream inp=new DataInputStream(cs.getInputStream());

DataOutputStream out=new DataOutputStream(cs.getOutputStream());System.out.println("A. UPLOAD");System.out.println("B. DOWNLOAD");System.out.print("ENTER THE OPTION:");option=in.readLine();out.writeBytes(option+"\n");if(option.compareTo("A")==0){

System.out.println("Enter the file name:");

17

Page 18: Lab Manual CN(Odd Sem)

fname=in.readLine();System.out.println("Enter the file name to be saved in Server:");

f1name=in.readLine();out.writeBytes(f1name+'\n');File f=new File(fname);FileInputStream fi=new FileInputStream(fname);size=fi.available();byte b[]=new byte[size];fi.read(b);fi.close();out.write(b);System.out.println("UPLOADED!!!!!");

}else if(option.compareTo("B")==0){

System.out.println("Enter the file name :");fname=in.readLine();System.out.println("Enter the file name to be saved :");f1name=in.readLine();out.writeBytes(fname+'\n');byte b[]=new byte[400];inp.read(b);File f=new File(f1name);FileOutputStream fo=new FileOutputStream(f1name);fo.write(b);fo.close();System.out.println("DOWNLOADED!!!!!");

}else {

System.out.println("Enter Valid Option");}cs.close();end = System.currentTimeMillis();

}}

File Serverimport java.io.*;import java.net.*;class FileServer{

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

String fname, f1name, option;DataInputStream in=new DataInputStream(System.in);

18

Page 19: Lab Manual CN(Odd Sem)

ServerSocket ss=new ServerSocket(6789);while(true){

Socket s=ss.accept();DataInputStream inp=new DataInputStream(s.getInputStream());DataOutputStream out=new DataOutputStream(s.getOutputStream());

option=inp.readLine();if(option.compareTo("A")==0){

f1name=inp.readLine();try{

File f=new File(f1name);FileOutputStream fo=new FileOutputStream(f);byte b[]=new byte[400];inp.read(b);fo.write(b);fo.close();

System.out.println("File "+f1name+" UPLOADED!!!!!");}catch(FileNotFoundException e){

String excep = "Sorry... File Not Present";System.out.println(excep);break;

}}else if(option.compareTo("B")==0){

fname=inp.readLine();try{

File f=new File(fname);InputStream fi=new FileInputStream(f);System.out.println("Accessed file :" + fname);int size=fi.available();byte b[]=new byte[size];fi.read(b);fi.close();out.write(b);System.out.println("Successfully send");

} catch(FileNotFoundException e){

String excep = "Sorry... File Not Present";System.out.println(excep);

19

Page 20: Lab Manual CN(Odd Sem)

break;}

}else{

System.out.println("Enter Valid Option");}

} } }

Output

RESULTThus a program is written to perform functions with default arguments

20