• No results found

COMPUTER NETWORKS LAB MANUAL

N/A
N/A
Protected

Academic year: 2021

Share "COMPUTER NETWORKS LAB MANUAL"

Copied!
32
0
0

Loading.... (view fulltext now)

Full text

(1)

K.L.N. COLLEGE OF ENGINEERING

Pottapalayam Post - 630 612.

Sivagangai District, Tamil Nadu.

DEPARTMENT OF INFORMATION TECHNOLOGY

IT6511-NETWORKS LABORATORY MANUAL

Staff In-Charges and Prepared by

Mr.S.Ilangovan, ASP/IT

Mr.S.Ramesh, AP2/IT

III Year/V Semester

(July 2015-November 2015)

(2)

IT6511

NETWORKS LABORATORY

L T P C

0 0 3 2

OBJECTIVES:

The student should be made to:  Learn socket programming.  Be familiar with simulation tools.

 Have hands on experience on various networking protocols. LIST OF EXPERIMENTS:

1. Implementation of Stop and Wait Protocol and Sliding Window Protocol. 2. Study of Socket Programming and Client – Server model

3. Write a code simulating ARP /RARP protocols.

4. Write a code simulating PING and TRACEROUTE commands 5. Create a socket for HTTP for web page upload and download. 6. Write a program to implement RPC (Remote Procedure Call) 7. Implementation of Subnetting .

8. Applications using TCP Sockets like a. Echo client and echo server b. Chat

c. File Transfer

9. Applications using TCP and UDP Sockets like d. DNS

e. SNMP f. File Transfer

10. Study of Network simulator (NS).and Simulation of Congestion Control Algorithms using NS

11. 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 ii. Flooding

iii. Distance vector

TOTAL: 45 PERIODS

(3)

K.L.N. College of Engineering, Pottapalayam – 630612.

Department of Information Technology

LAB PLAN

Subject Name: Networks Lab Branch: IT

Subject Code: IT6511 Year/Sem/Sec: III/V/A

Name of the Faculty: Mr.S.Ramesh, M.E., M.B.A., Faculty Code: 10535027

Ex.No

Date

Name of the Experiment

1 01-07-15 Study of Socket Programming and Client – Server model. 2 08-07-15 Chat Application using TCP Sockets.

3 15-07-15 Echo client and echo server using TCP Sockets. 4 22-07-15 File transfer using TCP Sockets.

5 29-07-15 Write a code simulating PING commands.

6 05-08-15 Write a code simulating TRACEROUTE commands. 7 08-08-15 Write a program to implement RPC (Remote Procedure

Call).

8 12-08-15 Implementation of Stop and Wait Protocol and Sliding Window Protocol.

9 19-08-15 Write a code simulating ARP /RARP protocols. 10 26-08-15 Create a socket for HTTP for web page upload and

download.

11 02-09-15 Study of Network simulator (NS).

12 09-09-15 Two Nodes and four nodes creation using NS2.

13 16-09-15 Revision - 1

14 23-09-15 Revision - 2

15 30-09-15 Model Lab Exam

(4)

Staff In-charge HOD/IT

K.L.N College Of Engineering, Pottapalayam – 630612

Department of Information Technology

LAB PLAN

Subject Name: Networks Lab Branch: Information Technology

Subject Code: IT6511 Year/Sem/Sec: III/V/B

Name of the Faculty: Mr.S.ILANGOVAN, Faculty Code: 10535021

Ex.No

Date

Name of the Experiment

1 03-07-15 Study of Socket Programming and Client – Server model. 2 10-07-15 Chat Application using TCP Sockets.

3 17-07-15 Echo client and echo server using TCP Sockets. 4 24-07-15 File transfer using TCP Sockets.

5 31-07-15 Write a code simulating PING commands.

6 07-08-15 Write a code simulating TRACEROUTE commands. 7 14-08-15 Write a program to implement RPC (Remote Procedure

Call).

8 21-08-15 Implementation of Stop and Wait Protocol and Sliding Window Protocol.

9 28-08-15 Write a code simulating ARP /RARP protocols. 10 04-09-15 Create a socket for HTTP for web page upload and

download.

11 11-09-15 Study of Network simulator (NS).

12 12-09-15 Two Nodes and four nodes creation using NS2.

13 18-09-15 Revision - 1

14 25-09-15 Revision - 2

15 09-10-15 Model Lab Exam

(5)

Staff In-charge HOD/IT

Ex.No.1a

STUDY OF SOCKET PROGRAMMING

AIM:

To study about socket programming for developing the client server application.

DESCRIPTION

A socket is an endpoint for communication. Two processes can communicate by creating sockets and sending messages between them. A socket type is uniquely determined by a <domain, type, protocol> triple.

a= socket(addressfamily,type of socket,protocol)

addressfamily=AF_INET type of socket=SOCK_STREAM (or) SOCK_DGRAM protocol= 0 (for system default protocol) a=unique descriptor

In order to hold information about the socket, socket address structures are used.

int bind (socket descriptor, socket address structure, sizeof(socketaddressstructure)) return 0 if OK,-1 on error int listen( int sockfd, int backlog)

return 0 if OK,-1 on error

int accept(int sockfd, void *addr, void *addrlen); return positive value if OK, -1 on error

int connect(int sockfd, socket address structure, sizeof(socketaddressstructure))

RESULT:

(6)

Exp. No.1b

SOCKET CREATION

AIM

To write a C program for creating a socket

ALGORITHM

1. Include the necessary header files.

2. Declare 2 variables as TCP and UDP file descriptors for holding the values of TCP and UDP socket.

3. Call the System function Socket ( ) with the following parameters type of family, type of socket and type of protocol for creating the socket.

4. If the System function returns negative value then the print error message else print socket created with socket value.

Exp. No.1c

SOCKET BINDING

AIM

To write a C program for socket binding

ALGORITHM

1. Include the necessary header files.

2. Declare 2 variables as TCP and UDP file descriptors for holding the values of 3. TCP and UDP socket.

4. Call the System function socket() with the following parameters type of family, type of socket and type of protocol for creating the socket.

5. Call the system function bind() with the following parameters socket descriptor, socket address structure and size of socket address structure.

RESULT:

(7)

Exp. No.2

CLIENT – SERVER CHAT USING TCP/IP

Aim:

To write a C program for client – server chat using TCP

Theory

TCP

TCP stands for Transaction Control Protocol. This is one of the transport layer protocols. TCP offers a

connection-oriented, reliable, byte stream service. This also provides a good flow control and

congestion control. The term connection-oriented means any two applications using TCP must establish a connection with each other before they can exchange data. This can be done by using three-way handshaking.

Data is divided into small chunks and each chunk of data is called as Segments. The data sent using TCP follows a single route and it can be in out-of-order. The receiver will rearrange the data using the sequence numbers.

Flow control is established by using a finite amount of buffer space on both sides. With this the receiver allows the sender to send only the amount of data it can accept in the buffer. TCP also provides error control. A checksum is maintained in the header and data.

Services provided by TCP

• Connection- oriented: setup required between client, server • Reliable transport between sending and receiving process

• Flow control: sender won’t overwhelm receiver

• Congestion control: throttle sender when network overloaded Services not provided by TCP

• Timing and minimum bandwidth Algorithm

Server

1. Start the program.

2. Include all the necessary header files and declare necessary variables.

3. Create a stream socket “sersock” using socket() and check if the socket is created successfully or not.

4. Initialize the server socket structure variable – ser_ip(family, port & address).

5. Use bind() to assign the local socket address ser_ip to the socket identified by sersock. 6. Accept the request to connect from the client by using the accept() and store the socket

information in nsersock.

7. Send and receive data to and from the client by using send () & recv() respectively. Print the received data.

8. Goto step 7 until client sends “exit”. 9. Close all open sockets.

10. Stop the program.

Client

(8)

2. Include all the necessary header files and declare necessary variables.

3. Create a stream socket “clisock” using socket() and check if the socket is created successfully of not.

4. Initialize the client socket structure variable – cli_ip(family, port & address). 5. Send a request to connect with the server using connect().

6. Send and receive data to and from server using send() & recv() respectively. 7. Repeat step 6 until either of the users wants to quit by typing “exit”.

8. Close all open sockets. 9. Stop the program. Program

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

public class Serverchat{

public static void main(String[]args)throws IOException{ ServerSocket sock=null; BufferedReader fromClient=null,fromUser=null; PrintWriter toClient=null; Socket client=null; try{ sock=new ServerSocket(4444); System.out.println("Server Ready"); client=sock.accept(); System.out.println("Client connected"); fromClient=new BufferedReader(new InputStreamReader(client.getInputStream())); toClient=new PrintWriter(client.getOutputStream());

fromUser=new BufferedReader(new InputStreamReader(System.in)); String line,Usermsg; while(true){ line=fromClient.readLine(); if((line==null) || (line.equals("bye"))) break; System.out.println("Client:" +line); System.out.print("me:"); Usermsg=fromUser.readLine(); toClient.println(Usermsg); toClient.flush(); } fromClient.close(); toClient.close(); client.close(); System.out.println("Client disconnected"); } catch(IOException ioe){ System.out.println(ioe); } } } Clientchat

(9)

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

public class Clientchat{

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(),4444); else sock=new Socket(InetAddress.getByName(args[0]),4444); fromServer=new BufferedReader(new InputStreamReader(sock.getInputStream()));

fromUser=new BufferedReader(new InputStreamReader(System.in)); toServer=new PrintWriter(sock.getOutputStream(),true);

String Usermsg,Servmsg;

System.out.println("Type \"bye\" to quit"); while(true){ System.out.print("me:"); Usermsg=fromUser.readLine(); if(Usermsg==null||Usermsg.equals("bye")){ toServer.println("bye"); break; } else toServer.println(Usermsg); Servmsg=fromServer.readLine(); System.out.println("Server:" +Servmsg); } fromUser.close(); fromServer.close(); toServer.close(); sock.close(); } catch(IOException ioe){ System.err.println(ioe); } } } Result

Thus the C program for client-server chat using TCP is written, entered, executed and the results are verified.

(10)

EX.NO:3 ECHO CLIENT AND SERVER USING TCP SOCKETS

AIM:

To implementation of echo client server using TCP/IP

ALGORITHM:

1.start the program

2 To create a socket in client to server.

3. 3he client establishes a connection to the server.

4. The client accept the connection and send data to server and the server to replay the echo message to the client

5. The client communicate the server to send the end of the message 6. Stop the program.

Program

Server

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

public class Serverecho{

public static void main(String[]args)throws IOException{ ServerSocket sock=null; BufferedReader fromClient=null; OutputStreamWriter toClient=null; Socket client=null; try{ sock=new ServerSocket(4444); 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+ "]\n"); toClient.write("server[" +line+ "]\n"); toClient.flush(); } fromClient.close(); toClient.close();

(11)

client.close(); System.out.println("Client disconnected"); } catch(IOException ioe){ System.out.println(ioe); } }} Client import java.net.*; import java.io.*;

public class Clientecho{

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(),4444); else sock=new Socket(InetAddress.getByName(args[0]),4444); fromServer=new BufferedReader(new InputStreamReader(sock.getInputStream()));

fromUser=new BufferedReader(new InputStreamReader(System.in)); toServer=new PrintWriter(sock.getOutputStream(),true);

String Usermsg,Servmsg;

System.out.println("Type \"bye\" to quit"); while(true){ System.out.println("Enter msg to server:"); Usermsg=fromUser.readLine(); if(Usermsg.equals("bye")){ toServer.println("bye"); break; } else toServer.println(Usermsg); Servmsg=fromServer.readLine(); System.out.println(Servmsg); } fromUser.close(); fromServer.close(); toServer.close(); sock.close(); } catch(IOException ioe){ System.err.println(ioe); } } } Result

(12)

Ex.No : 4 File transfer using TCP sockets

Aim

To write a java program for applaction using TCP Sockets Algorithm

1.Start the program.

2.Get the frame size from the user

3.To create the frame based on the user request. 4.To send frames to server from the client side.

5.If your frames reach the server it will send ACK signal to client otherwise it will send NACK signal to client.

6.Stop the program Program

Clientfile

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

import java.lang.String; public class ClientFile{

public static void main(String [] args)throws IOException{ int i; //String s="ServerFile.txt"; InputStream is=null; BufferedOutputStream bos=null; Socket sock=null; try{ if(args.length==0) sock=new Socket(InetAddress.getLocalHost(),4000); else sock=new Socket(InetAddress.getByName(args[0]),4000); System.out.println("Connecting..."); String s1="clientFile.txt"; File myfile = new File(s1); byte [] arrayy=new byte[1500]; is=sock.getInputStream();

bos=new BufferedOutputStream(new FileOutputStream(myfile)); i=is.read(arrayy,0,arrayy.length); bos.write(arrayy,0,i); bos.flush(); } catch(IOException ioe){ System.out.println(ioe); }

(13)

} } Serverfile import java.net.*; import java.io.*; import java.lang.String; public class ServerFile{

public static void main(String [] args)throws IOException{ ServerSocket sock=null; BufferedInputStream bis=null; Socket client=null; OutputStream os=null; int a; try{ sock=new ServerSocket(4000); System.out.println("Waiting..."); client=sock.accept(); System.out.println("Server Ready");

System.out.println("Accepted connection:" +client); String s="ServerFile.txt";

File myfilee=new File(s);

byte [] array=new byte[(int)myfilee.length()];

bis=new BufferedInputStream(new FileInputStream(myfilee)); a=bis.read(array,0,array.length); os=client.getOutputStream(); os.write(array,0,a); os.flush(); } catch(IOException ioe){ System.out.println(ioe); } } } Result

(14)

EX-NO. 5 Write a Code simulating PING and TRACEROUTE

Commands

Aim:

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

1.Start the program.

2.Get the frame size from the user

3.To create the frame based on the user request. 4.To send frames to server from the client side.

5.If your frames reach the server it will send ACK signal to client otherwise it will send NACK signal to client.

6.Stop the program Program //pingclient.java import java.io.*; import java.net.*; import java.util.Calendar; class pingclient {

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

String str; int c=0; long t1,t2;

Socket s=new Socket("127.0.0.1",5555);

DataInputStream dis=new DataInputStream(s.getInputStream()); PrintStream out=new PrintStream(s.getOutputStream());

while(c<4) {

t1=System.currentTimeMillis();

str="Welcome to network programming world"; out.println(str); System.out.println(dis.readLine()); t2=System.currentTimeMillis(); System.out.println(";TTL="+(t2-t1)+"ms"); c++; } s.close(); } }

(15)

//pingserver.java import java.io.*; import java.net.*; import java.util.*; import java.text.*; class pingserver {

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

ServerSocket ss=new ServerSocket(5555); Socket s=ss.accept();

int c=0; while(c<4) {

DataInputStream dis=new DataInputStream(s.getInputStream()); PrintStream out=new PrintStream(s.getOutputStream());

String str=dis.readLine(); out.println("Reply from"+InetAddress.getLocalHost()+";Length"+str.length()); c++; } s.close(); } } Result:

(16)

Ex.No:7 Write a program to implement RPC

Aim:

To write a java program to implement RPC (remote procedure call

Algorithm :

1.Start the program.

2.Get the frame size from the user

3.To create the frame based on the user request. 4.To send frames to server from the client side.

5.If your frames reach the server it will send ACK signal to client otherwise it will send NACK signal to client.

6.Stop the program

Program: RPC 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); } } } Server import java.io.*; import java.net.*;

(17)

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

(18)

Result :

Thus the program was implementing to implement RPC (remote procedure call)

Ex.No:8

Implementation of Stop and Wait Protocol and Sliding Window

Protocol

AIM:

To write a java program to perform sliding window.

ALGORITHM:

1.Start the program.

2.Get the frame size from the user

3.To create the frame based on the user request. 4.To send frames to server from the client side.

5.If your frames reach the server it will send ACK signal to client otherwise it will send NACK signal to client.

6.Stop the program

Program :

import java.net.*; import java.io.*; import java.rmi.*; public class slidsender {

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; 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) {

System.out.println("Enter "+nf+" Messages to be send\n"); for(i=1;i<=nf;i++) { sbuff[sptr]=in.readLine(); p.println(sbuff[sptr]); sptr=++sptr%8; } sws-=nf;

(19)

System.out.print("Acknowledgment received"); ano=Integer.parseInt(in1.readLine());

System.out.println(" for "+ano+" frames"); sws+=nf;

} else {

System.out.println("The no. of frames exceeds window size"); break;

}

System.out.print("\nDo you wants to send some more frames : "); ch=in.readLine(); p.println(ch); } while(ch.equals("yes")); s.close(); } } 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 { 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")); } }

(20)

OUTPUT:

//SENDER OUTPUT

Enter the no. of frames : 4 Enter 4 Messages to be send hiii

how r u i am fine how is evryone

Acknowledgment received for 4 frames Do you wants to send some more frames : no

//RECEIVER OUTPUT

The received Frame 0 is : hiii The received Frame 1 is : how r u The received Frame 2 is : i am fine The received Frame 3 is : how is everyone

Result

(21)

Ex.No:9 Write a code simulating ARP /RARP protocols

.

Aim:

To write a java program for simulating arp/rarp protocols

ALGORITHM: server

1. Create a server socket and bind it to port.

2. Listen for new connection and when a connection arrives, accept it. 3. Send server‟s date and time to the client.

4. Read client‟s IP address sent by the client. 5. Display the client details.

6. Repeat steps 2-5 until the server is terminated. 7. Close all streams.

8. Close the server socket. 9. Stop.

Client

1. Create a client socket and connect it to the server‟s port number. 2. Retrieve its own IP address using built-in function.

3. Send its address to the server.

4. Display the date & time sent by the server. 5. Close the input and output streams.

6. Close the client socket. 7. Stop.

Program

Program for Address Resolutuion Protocol (ARP) using TCP Client: import java.io.*; import java.net.*; import java.util.*; class Clientarp {

public static void main(String args[]) {

Try {

BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); Socket clsct=new Socket("127.0.0.1",139);

DataInputStream din=new DataInputStream(clsct.getInputStream()); DataOutputStream dout=new DataOutputStream(clsct.getOutputStream()); System.out.println("Enter the Logical address(IP):");

String str1=in.readLine(); dout.writeBytes(str1+'\n'); String str=din.readLine();

(22)

clsct.close(); } catch (Exception e) { System.out.println(e); } } } Server: import java.io.*; import java.net.*; import java.util.*; class Serverarp {

public static void main(String args[]) {

try {

ServerSocket obj=new ServerSocket(139); Socket obj1=obj.accept();

while(true) {

DataInputStream din=new DataInputStream(obj1.getInputStream()); DataOutputStream dout=new DataOutputStream(obj1.getOutputStream()); String str=din.readLine(); String ip[]={"165.165.80.80","165.165.79.1"}; String mac[]={"6A:08:AA:C2","8A:BC:E3:FA"}; for(int i=0;i<ip.length;i++) { if(str.equals(ip[i])) { dout.writeBytes(mac[i]+'\n'); break; } } obj.close(); } } catch(Exception e) { System.out.println(e); } } } Output: E:\networks>java Serverarp E:\networks>java Clientarp Enter the Logical address(IP):

(23)

165.165.80.80

The Physical Address is: 6A:08:AA:C2

Program for Reverse Address Resolutuion Protocol (RARP) using UDP Client: import java.io.*; import java.net.*; import java.util.*; class Clientrarp12 {

public static void main(String args[]) {

try {

DatagramSocket client=new DatagramSocket();

InetAddress addr=InetAddress.getByName("127.0.0.1"); byte[] sendbyte=new byte[1024];

byte[] receivebyte=new byte[1024];

BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the Physical address (MAC):");

String str=in.readLine(); sendbyte=str.getBytes();

DatagramPacket sender=new DatagramPacket(sendbyte,sendbyte.length,addr,1309); client.send(sender);

DatagramPacket receiver=new DatagramPacket(receivebyte,receivebyte.length); client.receive(receiver);

String s=new String(receiver.getData());

System.out.println("The Logical Address is(IP): "+s.trim()); client.close(); } catch(Exception e) { System.out.println(e); } } } Server: import java.io.*; import java.net.*; import java.util.*; class Serverrarp12 {

public static void main(String args[]) {

try {

(24)

while(true) {

byte[] sendbyte=new byte[1024]; byte[] receivebyte=new byte[1024];

DatagramPacket receiver=new DatagramPacket(receivebyte,receivebyte.length); server.receive(receiver);

String str=new String(receiver.getData()); String s=str.trim(); //System.out.println(s); InetAddress addr=receiver.getAddress(); int port=receiver.getPort(); String ip[]={"165.165.80.80","165.165.79.1"}; String mac[]={"6A:08:AA:C2","8A:BC:E3:FA"}; for(int i=0;i<ip.length;i++) { if(s.equals(mac[i])) { sendbyte=ip[i].getBytes();

DatagramPacket sender=new DatagramPacket(sendbyte,sendbyte.length,addr,port); server.send(sender); break; } } break; } } catch(Exception e) { System.out.println(e); } } } Output: I:\ex>java Serverrarp12 I:\ex>java Clientrarp12

Enter the Physical address (MAC): 6A:08:AA:C2

(25)

Result :

Thus the program for implementing to display simulating ARP /RARP protocols.

Ex.No:10 Create a socket for HTTP for web page upload and

download.

Aim:

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

Algorithm

1.Start the program.

2.Get the frame size from the user

3.To create the frame based on the user request. 4.To send frames to server from the client side.

5.If your frames reach the server it will send ACK signal to client otherwise it will send NACK signal to client.

6.Stop the program Program : Client import javax.swing.*; import java.net.*; import java.awt.image.*; import javax.imageio.*; import java.io.*; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public class Client{

public static void main(String args[]) throws Exception{ Socket soc;

BufferedImage img = null;

soc=new Socket("localhost",4000); System.out.println("Client is running. ");

try {

System.out.println("Reading image from disk. ");

img = ImageIO.read(new File("digital_image_processing.jpg")); ByteArrayOutputStream baos = new ByteArrayOutputStream();

ImageIO.write(img, "jpg", baos); baos.flush();

(26)

byte[] bytes = baos.toByteArray(); baos.close();

System.out.println("Sending image to server. "); OutputStream out = soc.getOutputStream(); DataOutputStream dos = new DataOutputStream(out); dos.writeInt(bytes.length);

dos.write(bytes, 0, bytes.length);

System.out.println("Image sent to server. "); dos.close(); out.close(); }catch (Exception e) { System.out.println("Exception: " + e.getMessage()); soc.close(); } soc.close(); } } Server import java.net.*; import java.io.*; import java.awt.image.*; import javax.imageio.*; import javax.swing.*; class Server {

public static void main(String args[]) throws Exception{ ServerSocket server=null;

Socket socket;

server = new ServerSocket(4000);

System.out.println("Server Waiting for image"); socket = server.accept();

System.out.println("Client connected.");

InputStream in = socket.getInputStream();

DataInputStream dis = new DataInputStream(in); int len = dis.readInt();

System.out.println("Image Size: " + len/1024 + "KB");

byte[] data = new byte[len]; dis.readFully(data);

dis.close(); in.close();

InputStream ian = new ByteArrayInputStream(data); BufferedImage bImage = ImageIO.read(ian);

JFrame f = new JFrame("Server");

ImageIcon icon = new ImageIcon(bImage); JLabel l = new JLabel();

(27)

l.setIcon(icon); f.add(l); f.pack(); f.setVisible(true); } } Download import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL;

public class Download {

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

try{

String fileName = "digital_image_processing.jpg";

String website = "http://tutorialspoint.com/java_dip/images/"+fileName;

System.out.println("Downloading File From: " + website);

URL url = new URL(website);

InputStream inputStream = url.openStream();

OutputStream outputStream = new FileOutputStream(fileName); byte[] buffer = new byte[2048];

int length = 0;

while ((length = inputStream.read(buffer)) != -1) { System.out.println("Buffer Read of length: " + length); outputStream.write(buffer, 0, length); } inputStream.close(); outputStream.close(); }catch(Exception e){ System.out.println("Exception: " + e.getMessage()); } } } Output

(28)

Result

Thus the web page was uploaded and downloaded successfully using HTTP Sockets.

Exp. No.11

Study of Network simulator (NS).

Network Simulator:

A network simulator is a piece of software or hardware that predicts the behavior of a network, without an actual network being present.

Uses of network simulators:

1. 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.

2. They allow engineers to test scenarios that might be particularly difficult or expensive to emulate using real hardware. For an instance, simulating the effects of a sudden burst in traffic or a DoS attack on a network service.

3. Networking simulators are particularly useful in allowing designers to test new networking protocols or changes to existing protocols in a controlled and reproducible environment.

4. Network simulators, as the name suggests are used by researchers, developers and QA to design various kinds of networks, simulate and then analyze the effect of various parameters on the network performance.

5.A typical network simulator encompasses a wide range of networking technologies

and help the users to build complex networks from basic building blocks like variety of nodes and links.

6. 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. 7. 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.

(29)

used to handle network traffic.

9. 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.

GTNets, are programming-oriented, providing a programming framework that the user then customizes to create an application that simulates the networking environment to be tested.

Exp. No.12 NS-2 WITH 2 NODES

Aim:

To Develop the Simulation for the network with 2 nodes and 1 link. Theory

First of all, you need to create a simulator object. This is done with the command

set ns [new Simulator]

Now we open a file for writing that is going to be used for the nam trace data.

set nf [open out.nam w] $ns namtrace-all $nf

The first line opens the file 'out.nam' for writing and gives it the file handle 'nf'. In the second line we tell the simulator object that we created above to write all simulation data that is going to be relevant for nam into this file.The next step is to add a 'finish' procedure that closes the trace file and starts nam.

proc finish {} { global ns nf $ns flush-trace close $nf

exec nam out.nam & exit 0

}

The next line tells the simulator object to execute the 'finish' procedure after 5.0 seconds of simulation time.

$ns at 5.0 "finish"

# Insert your own code for topology creation # and agent definitions, etc. here

#Call the finish procedure after 5 seconds simulation time $ns at 5.0 "finish"

#Run the simulation $ns run

Algorithm

1. Create a simulator object 2. open the nam trace file

3. Define the finish procedure that closes the trace file. KLNCE/Dept – IT 17

(30)

Networks Lab

4. Create two nodes no and n1

5. Create a duplex link between the nodes. 6. Create a UDP agent and attach it to node no 7. Create a CBR traffic source and attach it to udp0

8. Create a Null agent which act as a traffic sink and attach it to node n1 9. Connect two agents

10. Set the time for one agent to send data and another agent to receive data. 11. Call the finish procedure after 5 seconds of simulation time

12. Run the Simulation Result

Thus the simulation for the network with 2 nodes was developed successfully.

NS-2 WITH 4 NODES

Aim:

To develop the Simulation for the network with 4 nodes Algorithm

1. Create a simulator object 2. open the nam trace file

3. Define the finish procedure that closes the trace file. 4. Create four nodes no,n1,n2 and n3.

5. Create one duplex link between the node no and n1. 6. Create one duplex link between the node no and n2. 7. Create one duplex link between the node n2 and n3. 8. Create a UDP agent and attach it to node n0

9. Create a UDP agent and attach it to node n1. 10. Create a UDP agent and attach it to node n2. 11. Create a Null agent and attach it to node n3. 12. Create a CBR traffic source and attach it to udp0 13. Create a CBR traffic source and attach it to udp1. 14. Create a CBR traffic source and attach it to upp2. 15. Connect agent0 and agent2.

16. Connect agent1 and agent2. 17. Connect agent2 and agent3.

18. Set the time for one agent to send data and another agent to receive data. 19. Call the finish procedure after 5 seconds of simulation time

20. Run the Simulation. Program

set ns [new Simulator] $ns color 1 Blue $ns color 2 Red

set nf [open out.nam w] $ns namtrace-all $nf proc finish {} { global ns nf $ns flush-trace close $nf

(31)

exec nam out.nam & exit 0 } set n0 [$ns node] set n1 [$ns node] set n2 [$ns node] set n3 [$ns node] $ns duplex-link $n0 $n2 2Mb 10ms DropTail $ns duplex-link $n1 $n2 2Mb 10ms DropTail $ns duplex-link $n2 $n3 1.7Mb 20ms DropTail $ns queue-limit $n2 $n3 10

$ns duplex-link-op $n0 $n2 orient right-down $ns duplex-link-op $n1 $n2 orient right-up $ns duplex-link-op $n2 $n3 orient right $ns duplex-link-op $n2 $n3 queuePos 0.5 set tcp [new Agent/TCP]

$tcp set class_ 2

$ns attach-agent $n0 $tcp set sink [new Agent/TCPSink] $ns attach-agent $n3 $sink $ns connect $tcp $sink $tcp set fid_ 1

set ftp [new Application/FTP] $ftp attach-agent $tcp

$ftp set type_ FTP

set udp [new Agent/UDP] $ns attach-agent $n1 $udp set null [new Agent/Null] $ns attach-agent $n3 $null $ns connect $udp $null $udp set fid_ 2

set cbr [new Application/Traffic/CBR] $cbr attach-agent $udp

$cbr set type_ CBR

$cbr set packet_size_ 1000 $cbr set rate_ 1mb

$cbr set random_ false $ns at 0.1 "$cbr start" $ns at 1.0 "$ftp start" $ns at 4.0 "$ftp stop" $ns at 4.5 "$cbr stop"

$ns at 4.5 "$ns detach-agent $n0 $tcp ; $ns detach-agent $n3 $sink" $ns at 5.0 "finish"

puts "CBR packet size = [$cbr set packet_size_]" puts "CBR interval = [$cbr set interval_]"

(32)

Result

References

Related documents

TCP Overview Machine A Machine B Processus client Processus serveur Socket d'écoute 2a.- connect 1a.- socket 1b.- socket 2b.- bind 3b.- listen 4b.- accept Socket de

sck – socket descriptor (from socket function) name – sockaddr_in structure with socket IP address and port number. sin_family – AF_INET –

However, IPv4 ignores any ancillary data associated with the sendmsg() call, so it is necessary to create a separate reply socket and bind it to the desired local source address.

To initiate a connection, the client program in Code Example 2-2 creates a stream socket and calls connect() , specifying the address of the socket to connect to.. If the target

Line 17-18 : Connect function establishes TCP connection with server specified by the socket address structure pointed to by &amp;servaddr which we set in line 15..

connect Creates a connection between two sockets bind Labels a server socket with an address listen Configures a socket to accept conditions. accept Accepts a connection and creates

This function takes three parameters: the file descriptor of a newly created socket, the address and port of the server it should connect to (cast to a struct sockaddr), and the size

• The bind() system call is used to assign an address to an existing socket. int bind(