Sie sind auf Seite 1von 53

Ex. No.

1(a) Stop And Wait Protocol


Date:

Aim:
To Write a C program to implement Stop And Wait Protocol.

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.
6. The client waits for the ACK before transmitting the next frame.
7. Stop the program.

Program:

#include<stdio.h>
#define MAXSIZE 100
typedef struct
{
unsigned char data[MAXSIZE];
}packet;

typedef enum{data,ack}frame_kind;

typedef struct
{
frame_kind kind;
int sq_no;
int ack;
packet info;
}frame;

typedef enum{frame_arrival}event_type;
typedef enum{true_false}boolean;

void frame_network_layer(packet *p)


{
printf("\n from network arrival");
}

void to_physical_layer(frame *f)


{
printf("\n to physical layer");

1
}
void wait_for_event(event_type *e)
{
printf("\n waiting for event n");
}

void sender(void)
{
frame s;
packet buffer;
event_type event;
printf("\n ***SENDER***");
frame_network_layer(&buffer);
s.info=buffer;
to_physical_layer(&s);
wait_for_event(&event);
}

void from_physical_layer(frame *f)


{
printf("from physical layer");
}

void to_network_layer(packet *p)


{
printf("\n to network layer");
}

void receiver(void)
{
frame r,s;
event_type event;
printf("\n ***RECEIVER***");
wait_for_event(&event);
from_physical_layer(&r);
to_network_layer(&r.info);
to_physical_layer(&s);
}
main()
{
sender();
receiver();
}

2
Output

Result:
Thus the implementation of Stop and Wait Protocol was executed and Output was
verified successfully.

3
Ex. No.1(b) Sliding Window Protocol
Date:

Aim:
To implement Sliding Window Protocol using UNIX Operating System.

Algorithm:
1. Start the program
2. Initialize address to the required Variables.
3. Enter the frames to be transmitted.
4. Use the Sliding Window Protocol for transmitting the frames.
5. Display the Value.
6. Stop the Program.

Program:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
main()
{
char ch,frame[100]=”01230123”;
int i;
while(1)
{
printf(“\n\t\tSliding Window Simulation\n\n”);
printf(“\n\t\tSelective Repeat NARQ”);
printf(“\nEnter the frame:”);
scanf(“%s”,&frame);
printf(“\n\t\tSENDER\t\t\tRECEIVER”);
printf(“\n*******”);
for(i=0;i<strlen(frame);i++)
{
printf(“\nSliding:frame%c”,frame[i]);
if(rand()%4==3)
{
printf(“\tFrame%clost\tNAK for the frame%c\n”,frame[i],frame[i]);
printf(“\nSending:frame%c”,frame[i+1]);
printf(“\nSending:frame%c”,frame[i]);
i++;
}58
if(rand()%3==2)
printf(“\t\t\t\t\t ACK upto frame%c”,frame[i]);
}
}
}

4
Output:

Result:
Thus the implementation of Sliding Window Protocol was executed and Output was
verified successfully.

5
Ex. No. 2 Study of Socket Programming and Client – Server model
Date:

Aim :
To study about Socket Programming and Client – Server model.

Socket Programming and Client Server Model

In the client-server model, the client sends out requests to the server, and the server does
some processing with the request(s) received, and returns a reply (or replies) to the client. A
client (Internet Explorer, or Netscape) sends out a request for a particular web page, and the web-
server (which may be geographically distant, often in a different continent) receives and
processes this request, and sends out a reply, which in this case, is the web page that was
requested. The web page is then displayed on the browser (client).

Fig. Client-Server paradigm

Servers may be broadly classified into two types based on the way they serve requests
from clients.
1. Iterative servers
2. Concurrent servers

Iterative servers can serve only one client at a time. If two or more clients send in their
requests at the same time, one of them has to wait until the other client has received service.
Concurrent servers can serve multiple clients at the same time.

SOCKETS
Sockets (also called Berkeley Sockets, owing to their origin) can simply be defined as
end-points for communication. A socket provides us with an abstraction – or a logical end point
for communication. There are different types of sockets.
1. Stream sockets, of type SOCK_STREAM are used for connection oriented, TCP
connections.
2. Datagram sockets of type SOCK_DGRAM are used for UDP based applications.

Apart from these two, there are other socket types defined, like SOCK_RAW and
SOCK_SEQPACKET.

Socket layer, and the Berkeley Socket API


Figure shows the TCP/IP protocol stack, and shows where the “Socket layer” may be
placed. Sockets make use of the lower level network protocols, and provide the application

6
developer with an interface to the lower level network protocols. A library of system calls are
provided by the socket layer, and are termed as the “Socket API”. These system calls can be used
in writing socket programs.

Fig. TCP/IP protocol stack

Programming environment, and the WinSock library

We will study socket programming on the windows environment (Windows


9x/NT/2000/XP). Socket programming on UNIX based environments is similar, and most of the
system calls used are the same. Windows adds its own windows-specific extensions. Windows
provides the WinSock library which contains the system calls used for socket programming on
the windows environment.

BASIC SOCKET SYSTEM CALLS

Figure shows the sequence of system calls between a client and server for a connection-
oriented protocol.

1. The socket() system call

The socket() system call creates a socket and returns a handle to the socket created. The handle is
of data type SOCKET. In UNIX based environments, the socket descriptor is a non-negative
integer, but Windows uses the SOCKET data type for the same.

Socket handles may take any value in the range 0 to INVALID_SOCKET-1.

7
Fig. Socket system calls for connection-oriented case

Syntax

SOCKET sd = socket (int af, int type, int protocol);


Here, af is the Address family specification,
type is the socket type
protocol field is used to specify the protocol to be used with the address family specified.

8
The address family can be one of
 AF_INET (for Internet protocols like TCP, UDP)
 AF_UNIX (for Unix internal protocols)
 AF_NS, for Xerox network protocols
 AF_IMPLINK for the IMP link layer.

The type field is the socket type can be one of


 SOCK_STREAM for stream sockets (TCP connections)
 SOCK_DGRAM for datagram connections
 SOCK_RAW is used for raw sockets
 SOCK_SEQPACKET is used for a sequenced packet socket.

The protocol argument is typically set to 0.


We may also specify a protocol argument to use a specific protocol for your application.

2. The bind() system call


The bind() system call is used to specify the association <Local-Address—Local-Port>. It
is used to bind either connection oriented or connectionless sockets. The bind() function
basically associates a name to an unnamed socket. “name”, here refers to three components –
The address family, the host address, and the port number at which the application will provide
its service.

Syntax
int result = bind (SOCKET sd, const struct sockaddr* name, int namelen);

Here, sd is the SOCKET handle returned by the socket() system call before
name points to the SOCKADDR structure
namelen is the length of the parameter name in bytes.

3. The listen() system call


After creation of the socket, and binding to a local port, the server has to wait on
incoming connection requests. The listen() system call is used to specify the queue or backlog of
waiting (or incomplete) connections.

Syntax
int result = listen (SOCKET sd, int backlog);

Here,
sd is the SOCKET handle returned by the socket() system call before
backlog is the number of incoming connections that can be queued.

4. The accept() system call


After executing the listen() system call, a server waits for incoming connections. An
actual connection setup is completed by a call to accept(). accept() takes the first connection
request on the queue, and creates another socket with the same properties as sd (the socket
descriptor returned earlier by the socket() system call).

9
Syntax
SOCKET newsd = accept (SOCKET sd, struct sockaddr* addr, int* addrlen);
Here,
sd is the SOCKET handle returned by the socket() system call before
addr is a pointer to a buffer that receives the address of the connecting entity
addrlen is the length of the parameter addr.

5. The connect() system call


A client process also starts out by creating a socket by calling the socket() system call. It
uses connect() to connect that socket descriptor to establish a connection with a server. In the
case of a connection oriented protocol (like TCP/IP), the connect() system call results in the
actual connection establishment of a connection between the two hosts
Syntax
int result = connect (SOCKET sd, const struct sockaddr* servaddr, int addrlen);

Here,
sd is the SOCKET handle returned by the socket() system call before
servaddr is a pointer to the server’s address structure.
addrlen holds the length of this parameter.

6. send(), recv(), sendto() and recvfrom() system calls


After connection establishment, data is exchanged between the server and client using the
system calls send(), recv(), sendto() and recvfrom().
The syntax of the system calls are as below:
Syntax
int nbytes = send (SOCKET sd, const char* buf, int len, int flags);
int nbytes = recv (SOCKET sd, const char* buf, int len, int flags);
int nbytes = sendto (SOCKET sd, const char* buf, int len, int flags, struct sockaddr* to, int olen);
int nbytes = recvfrom (SOCKET sd, const char* buf, int len, int flags, struct sockaddr* from, int
fromlen);
7. The closesocket() system call
The closesocket() system call is used to close the connection. In some cases, any
remaining data that is queued is sent out before the closesocket() is executed.
Syntax

int result = closesocket (SOCKET sd);

Here, sd is the SOCKET handle returned by the socket() system call before.

8. The shutdown() system call


The shutdown() system call is used to disable sends or receives on a socket.
Syntax
int result = shutdown (SOCKET sd, int how);
Here,
sd is the SOCKET handle returned by the socket() system call before.

10
how determines how the shutdown is achieved.
The value of the parameter how is either any one of the following:

SD_RECEIVE, further receives on the socket will be disallowed.


SD_SEND, further sends are disallowed, and finally
SD_BOTH, both sends and receives on the socket are disallowed.

The shutdown() function does not close the socket. The socket is closed and all the associated
resources are freed only after a closesocket() call.

Important structs

Some of the structs used in the socket system calls are as follows:

struct sockaddr
{
unsigned short sa_family; /* address family, AF_xxx /

char sa_data[14]; /* 14 bytes of protocol address */


};

struct sockaddr_in {
short sin_family;
u_short sin_port;
struct in_addr sin_addr;
char sin_zero[8];
};

Header Files
1.#include <stdio.h>
This header file contains declarations used in most input and output and is typically
included in all C programs.
2.#include <sys/types.h>
This header file contains definitions of a number of data types used in system calls. These
types are used in the next two include files.
3. #include <sys/socket.h>
The header file socket.h includes a number of definitions of structures needed for sockets.
4. #include <netinet/in.h>
The header file netinet/in.h contains constants and structures needed for internet domain
addresses.
5. #include <netdb.h>
The file netdb.h defines the structure hostent.

Result:

Thus Socket Programming and Client – Server model was studied.

11
Ex. No. 3 ARP/RARP
Date:

Aim:
To write a C program To Simulate ARP/RARP.

Algorithm

SERVER
1. Create a server socket and client socket.
2. Create a process.
3. Get request from client.
4. Run the ipconfig –all command to find the physical address.
5. Send the physical address to the client.
6. Close server socket and client socket connection.

CLIENT
1. Create a client socket connection with specified port.
2. Read the message from the client.
3. Send the System name to the server.
4. Read the message from the server.
5. Print the message.
6. Close the client connection.

Program:

//ARP SERVER

#include<stdio.h>
#include<sys/types.h>
#include<sys/shm.h>
#include<string.h>
main()
{
int shmid, a, i;
char *ptr, *shmptr;
shmid=shmget(3000,10,IPC_CREAT | 0666);
shmptr=shmat(shmid,NULL,0);
ptr=shmptr;
for(i=0;i<3;i++)
{
puts("Enter the mac");
scanf("%s",ptr);
a=strlen(ptr);
printf("String length:%d",a);
ptr[a]= ' ' ;

12
puts("Enter IP address");
ptr=ptr+a+1;
scanf("%s",ptr);
ptr[a]='\n' ;
ptr= ptr+a+1;
}
ptr[strlen(ptr)]= '\0';
printf("\n ARP table at Serverside is=\n%s", shmptr);
shmdt(shmptr);
}

ARP table at Serverside is


a.b.c.d 1.2.3.4
e.f.g.h 5.6.7.8
i.j.k.l 9.1.2.3

//ARP CLIENT

#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<sys/shm.h>
main()
{
int shmid,a;
char *ptr, *shmptr;
char ptr2[51], ip[12], mac[26];
shmid=shmget(3000,10,0666);
shmptr=shmat(shmid,NULL,0);
puts("the arp table is");
printf("%s",shmptr);
printf("\n1.ARP\n 2.RARP\n 3.EXIT\n");
scanf("%d",&a);
switch(a)
{
case 1:
puts("Enter IP address");
scanf("%s",ip);
ptr=strstr(shmptr, ip);
ptr-=8;
sscanf(ptr,"%s%*s",ptr2);
printf("Mac address is %s",ptr2);

13
break;
case 2:
puts("Enter mac addr");
scanf("%s",mac);
ptr=strstr(shmptr, mac);
sscanf(ptr,"%*s%s",ptr2);
printf("IP address is %s",ptr2);
break;
case 3:
exit(1);
}
}

Output:

The arp table is


a.b.c.d 1.2.3.4
e.f.g.h 5.6.7.8
i.j.k.l 9.1.2.3

1.ARP
2.RARP
3.EXIT
Enter your choice: 1
Enter IP address: 1.2.3.4
Mac address is a.b.c.d

Enter your choice:2


Enter mac address: e.f.g.h
IP address is 5.6.7.8

Result:
Thus the C program to simulate ARP/RARP is written and executed successfully.

14
Ex. No. 4 Simulating Ping and Trace route Commands
Date:

Aim:
To write the java program for simulating ping and trace route commands.

Program:
import java.io.*;
import java.util.*;
public class JavaPingExampleProgram
{
public static void main(String args[])
throws IOException
{
// create the ping command as a list of strings
JavaPingExampleProgram ping = new JavaPingExampleProgram();
List<String> commands = new ArrayList<String>();
commands.add("ping");
commands.add("-c");
commands.add("5");
commands.add("74.125.236.73");
ping.doCommand(commands);
}
public void doCommand(List<String> command)
throws IOException
{
String s = null;
ProcessBuilder pb = new ProcessBuilder(command);
Process process = pb.start();
BufferedReader stdInput = new BufferedReader(new InputStreamReader
(process.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader
(process.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null)
{
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while((s = stdError.readLine()) != null)
{
System.out.println(s);
}
}

15
}

Output:

Pinging 127.0.0.1 with 32 bytes of data:


Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
1
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128

Ping statistics for 127.0.0.1:


Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 0ms, Maximum = 0ms, Average = 0ms

Result:
Thus the program was implementing to simulating ping and traceroute commands.

16
Ex. No. 5 Creating A Socket For HTTP For Web Page Upload And
Download
Date:

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:

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

17
JFrame f = new JFrame("Server");
ImageIcon icon = new ImageIcon(bImage);
JLabel l = new JLabel();
l.setIcon(icon);
f.add(l);
f.pack();
f.setVisible(true);
}
}

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

18
out.close();
}
catch (Exception e)
{
System.out.println("Exception: " + e.getMessage());
soc.close();
}
soc.close();
}
}

Output

When you run the client code, following output screen would appear on client side.

Result:

Thus the program was implementing to socket for HTTP for web page upload and
download.

19
Ex. No. 6 RPC (Remote Procedure Call)
Date:

Aim:
To write a program to add two numbers using RPC / RMI by providing Communication
between the Client and Server.

Algorithm:

AddClient
1. Start the program.
2. The Class AddClient provides Communication with the server.
3. It provides the rmi registry to store the two values.
4. Invokes the add function.

AddServer
1. It invokes the function of AddServerImpl.
2. The try function catch the Exception.
3. It contains the add() function and calculate the sum of the two values.

AddServerImpl
1. It contains the add() function and calculate the sum of two values.

AddServer Intf
1. Invokes the add() function to perform the operation.
2. Stop the program.

Program:

AddServer

import java.net.*;
import java.rmi.*;
public class AddServer
{
public static void main(String args[])
{
try
{
AddServerImpl addServerImpl=new AddServerImpl();
Naming.rebind("AddServer",addServerImpl);
}
catch(Exception e)
{
System.out.println("Exception:"+e);

20
}
}
}

AddClient

import java.rmi.*;
public class AddClient
{
public static void main(String args[])
{
try
{
String addServerURL="rmi://"+args[0]+"/AddServer";
AddServerIntf addServerIntf=(AddServerIntf)Naming.lookup(addServerURL);
System.out.println("The first number is"+args[1]);
double d1=Double.valueOf(args[1]).doubleValue();
System.out.println("The second number i"+args[2]);
double d2=Double.valueOf(args[2]).doubleValue();
System.out.println("the sum is "+addServerIntf.add(d1,d2));
}
catch(Exception e)
{
System.out.println("Exception:"+e);
}
}
}

AddServerImpl

import java.rmi.*;
import java.rmi.server.*;
public class AddServerImpl extends UnicastRemoteObject implements AddServerIntf
{
public AddServerImpl()throws RemoteException
{
}
public double add(double d1,double d2)throws RemoteException
{
return d1+d2;
}
}

21
AddServerIntf

import java.rmi.*;
public interface AddServerIntf extends Remote
{
double add(double d1,double d2)throws RemoteException;
}

Output:
AddServer

AddClient

Result:
Thus the Sum of two numbers was calculated using RPC/RMI protocol and Output was
verified successfully.

22
Ex. No. 7 Subnetting
Date:

Aim:
Write a program to implement subnetting and find the subnet masks.

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.util.Scanner;
class Subnet
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print(“Enter the ip address: “);
String ip = sc.nextLine();
String split_ip[] = ip.split(“\\.”); //SPlit the string after every .
String split_bip[] = new String[4]; //split binary ip
String bip = “”;
for(int i=0;i<4;i++)
{
split_bip[i] = appendZeros(Integer.toBinaryString(Integer.parseInt(split_ip[i]))); // “18” => 18
=> 10010 => 00010010
bip += split_bip[i];
}
System.out.println(“IP in binary is “+bip);
System.out.print(“Enter the number of addresses: “);
int n = sc.nextInt();
//Calculation of mask
int bits = (int)Math.ceil(Math.log(n)/Math.log(2)); /*eg if address = 120, log 120/log 2 gives log
to the base 2 => 6.9068, ceil gives us upper integer */
System.out.println(“Number of bits required for address = “+bits);
int mask = 32-bits;
System.out.println(“The subnet mask is = “+mask);
//Calculation of first address and last address
int fbip[] = new int[32];

23
for(int i=0; i<32;i++) fbip[i] = (int)bip.charAt(i)-48; //convert cahracter 0,1 to integer 0,1
for(int i=31;i>31-bits;i–)//Get first address by ANDing last n bits with 0
fbip[i] &= 0;
String fip[] = {“”,””,””,””};
for(int i=0;i<32;i++)
fip[i/8] = new String(fip[i/8]+fbip[i]);
System.out.print(“First address is = “);
for(int i=0;i<4;i++){
System.out.print(Integer.parseInt(fip[i],2));
if(i!=3) System.out.print(“.”);
}
System.out.println();
int lbip[] = new int[32];
for(int i=0; i<32;i++) lbip[i] = (int)bip.charAt(i)-48; //convert cahracter 0,1 to integer 0,1
for(int i=31;i>31-bits;i–)//Get last address by ORing last n bits with 1
lbip[i] |= 1;
String lip[] = {“”,””,””,””};
for(int i=0;i<32;i++)
lip[i/8] = new String(lip[i/8]+lbip[i]);
System.out.print(“Last address is = “);
for(int i=0;i<4;i++){
System.out.print(Integer.parseInt(lip[i],2));
if(i!=3) System.out.print(“.”);
}
System.out.println();
}
static String appendZeros(String s){
String temp = new String(“00000000″);
return temp.substring(s.length())+ s;
}
}

Output:

Enter the ip address: 100.110.150.10


IP in binary is 01100100011011101001011000001010
Enter the number of addresses: 7
Number of bits required for address = 3
The subnet mask is = 29
First address is = 100.110.150.8
Last address is = 100.110.150.15

Result:
Thus the Program was displayed implement subnetting and find the subnet masks.

24
Ex. No. 8 (a) Chat Application Using TCP Sockets
Date:

Aim:
To write a java program to perform the full duplex chat by sending and receiving the
message from the client to server and vice versa using TCP sockets.

Algorithm:

Server
1. Start the program.
2. Create a class for the server.
3. Declare the server socket and give the connection to the server.
4. Define the accept() to accept the server connection.
5. Declare the class DataInputStream for getting the Input data.
6. Declare the PrintStream to print the data.
7. The method readLine() get the input from the keyboard.
8. Display the message in the client.
9. Stop the Program.

Client
1. Start the program.
2. Create the class for client name.
3. Declare the InetAddress(Internet Address).
4. Declare the DataInputStream for getting the input data.
5. Declare the PrintStream for printing the input stream.
6. Here the st prints the Client Message in the server.
7. Stop.

Program:

Server

import java.net.*;
import java.io.*;
public class Server
{
public static void main(String args[])throws Exception
{
ServerSocket ss=new ServerSocket(3000);
Socket s=ss.accept();
System.out.println("My Server is Ready: ");
DataInputStream in=new DataInputStream(s.getInputStream());
PrintStream ps=new PrintStream(s.getOutputStream());
while(true)
{

25
String st=in.readLine();
System.out.println(st);
st=new DataInputStream(System.in).readLine();
ps.println("Server message= "+st);
}
}
}

Client
import java.net.*;
import java.io.*;
public class Client
{
public static void main(String args[])throws Exception
{
InetAddress ina=InetAddress.getLocalHost();
Socket s=new Socket(ina,3000);
System.out.println("My Client is Ready: ");
DataInputStream dis=new DataInputStream(s.getInputStream());
PrintStream ps=new PrintStream(s.getOutputStream());
while(true)
{
String st=new DataInputStream(System.in).readLine();
ps.println("Client message= "+st);
st=dis.readLine();
System.out.println(st);
}
}
}

26
Output

Server

Client

Result
Thus the full duplex chat by sending and receiving the message from the client to server
and vice versa using TCP socket is executed and the output is verified successfully.

27
Ex. No. 8 (b) TCP Echo Client/Server
Date:

Aim:

To implement echo server and client in java using TCP sockets.

Algorithm:

Eserver

1. Start the program.


2. Create a class for the EServer.
3. Declare the Server socket and give the Connection to the server.
4. Input the stream and print the stream ps.
5. Declare the accept() to accept the Server Connection.
6. Declare ‘I’ to get the inputstream.
7. Declare ‘ps’ for Printstream.
8. Stop the program.

EClient

1. Start the program.


2. Create a class for EClient.
3. Declare the Inet Address.
4. Declare os and get the output stream.
5. Declare DataInputStream for getting the input data.
6. Print the Client Message.
7. readLine() function is used to read the input from the keyboard.
8. Print the message.
9. Stop the Program.

Program:

Eserver
import java.net.*;
import java.io.*;
public class EServer
{
public static void main(String args[])throws Exception
{
ServerSocket ss=new ServerSocket(8020);
String line;
DataInputStream dis;
PrintStream ps;

28
Socket s;
s=ss.accept();
dis=new DataInputStream(s.getInputStream());
ps=new PrintStream(s.getOutputStream());
while(true)
{
line=dis.readLine();
ps.println(line);
}
}
}

EClient
import java.net.*;
import java.io.*;
public class EClient
{
public static void main(String args[])throws Exception
{
InetAddress ia=InetAddress.getLocalHost();
Socket c=new Socket(ia,8020);
String line;
DataInputStream is,is1;
PrintStream os;
os=new PrintStream(c.getOutputStream());
is=new DataInputStream(System.in);
is1=new DataInputStream(c.getInputStream());
while(true)
{
System.out.println("Client:");
line=is.readLine();
os.println(line);
System.out.println("Server:"+is1.readLine());
}
}
}

29
Output
EServer

EClient

Result

Thus the implementation of TCP/IP ECHO was executed and output was verified
successfully.

30
Ex. No. 8 (c) TCP File Transfer
Date:

Aim:

To implement file transfer in java using TCP sockets.

Algorithm:
Server
1. Start the Program.
2. Create a new file named sample.txt.
3. Create a class for the Serverfile.
4. Declare the Serversocket or give the connection to the server.
5. Define the accept() to accepts the server connection.
6. Declare the class DataInputStream forgetting the input data.
7. The method readLine() get the input from the keyboard.
8. Display the Client system address.
9. Stop the Program.

Client
1. Start the Program.
2. Create the class for the Clientfile.
3. Declare the Inet Address(Internet Address).
4. Declare the DataInputStream for getting input in the socket.
5. Declare the PrintStream for pointing the data in the server.
6. In print ‘id’ it will print the data in the server.
7. Stop the Program.

Program:
Server
import java.io.*;
import java.net.*;
import java.util.*;
class Serverfile
{
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();

31
FileReader f=new FileReader(str);
BufferedReader b=new BufferedReader(f);
String s;
while((s=b.readLine())!=null)
{
System.out.println(s);
dout.writeBytes(s+'\n');
}
f.close();
dout.writeBytes("-1\n");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Client
import java.io.*;
import java.net.*;
import java.util.*;
class Clientfile
{
public static void main(String args[])
{
try
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
Socket clsct=new Socket("127.0.0.1",139);
DataInputStream din=new DataInputStream(clsct.getInputStream());
DataOutputStream dout=new DataOutputStream(clsct.getOutputStream());
System.out.println("Enter the file name:");
String str=in.readLine();
dout.writeBytes(str+'\n');
System.out.println("Enter the new file name:");
String str2=in.readLine();
String str1,ss;
FileWriter f=new FileWriter(str2);
char buffer[];
while(true)
{
str1=din.readLine();
if(str1.equals("-1")) break;
System.out.println(str1);
buffer=new char[str1.length()];

32
str1.getChars(0,str1.length(),buffer,0);
f.write(buffer);
}
f.close();
clsct.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
}
Output:
File content
Computer networks
ISO/OSI
TCP/IP
Server/Client

Client
Enter the file name:
sample.txt

server
Computer networks
ISO/OSI
TCP/IP
Server/Client

client
Enter the new file name:
net.txt
Computer networks
ISO/OSI
TCP/IP
Server/Client

Destination file
Computer networks
ISO/OSI
TCP/IP
Server/Client

Result
Thus the implementation of application of File Transfer using TCP was executed and
output was verified successfully.

33
Ex. No. 9 (a) UDP Chat Server/Client
Date:

Aim:
To write a java program using UDP Socket to chat server and client.
Algorithm:
UDPserver:

1. Start the program.


2. Create a class UDPserver for the server.
3. Get the input from the keyboard and store it in buffer.
4. Buffered Reader is used to get the input from the buffer.
5. Length is used to determine the number of bytes need to store the line.
6. Stop the Program

UDPclient

1. Start the program.


2. Create the class UDPclient for client.
3. Get the input from the keyboard and store it in buffer.
4. Buffered Reader is used to get the input from the buffer.
5. InetAddress used to get the Internet Address.
6. Display the message.
7. Stop the program.

Program:

UDPserver

import java.io.*;
import java.net.*;
class UDPserver
{
public static DatagramSocket ds;
public static byte buffer[]=new byte[1024];
public static int clientport=789,serverport=790;
public static void main(String args[])throws Exception
{
ds=new DatagramSocket(clientport);
System.out.println("press Ctrl+c to quit the program");
BufferedReader dis=new BufferedReader(new InputStreamReader(System.in));
InetAddress ia=InetAddress.getLocalHost();

34
while(true)
{
DatagramPacket p=new DatagramPacket(buffer,buffer.length);
ds.receive(p);
String psx=new String(p.getData(),0,p.getLength());
System.out.println("Client:"+psx);
System.out.println("Server:");
String str=dis.readLine();
if(str.equals("end"))
break;
buffer=str.getBytes();
ds.send(new DatagramPacket(buffer,str.length(),ia,serverport));
}
}
}

UDPclient

import java.io.*;
import java.net.*;
class UDPclient
{
public static DatagramSocket ds;
public static int clientport=789,serverport=790;
public static void main(String args[])throws Exception
{
byte buffer[]=new byte[1024];
ds=new DatagramSocket(serverport);
BufferedReader dis=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Server waiting");
InetAddress ia=InetAddress.getLocalHost();
while(true)
{
System.out.println("Client:");
String str=dis.readLine();
if(str.equals("end"))
break;
buffer=str.getBytes();
ds.send(new DatagramPacket(buffer,str.length(),ia,clientport));
DatagramPacket p=new DatagramPacket(buffer,buffer.length);
ds.receive(p);
String psx=new String(p.getData(),0,p.getLength());
System.out.println("server:"+psx);
}
}
}

35
Output:

UDPserver

UDPclient

Result

Thus both the client and server exchange data using UDP sockets.

36
Ex.No. 9 (b) UDP Echo Server/Client
Date:

Aim:
To implement echo server and client in java using UDP sockets.
Algorithm:
Server
1. Create a datagram socket.
2. Receive client's message in a datagram packet.
3. Read Client's message and display it.
4. Convert text from client to upper case and send it back to client.
5. Repeat steps 2-4 until the client has something to send.
6. Close the server socket.
7. Stop.
Client
1. Create a datagram socket.
2. Get a message from user.
3. Construct a datagram packet and send it to server.
4. Create a datagram packet to receive echoed message.
5. Read server's response and display it.
6. Repeat steps 2-5 until there is some text to send.
7. Close the client socket.
8. Stop.

Program:
UDPEchoServer
import java.net.*;
class UDPEchoServer
{
public static void main(String args[]) throws Exception
{
DatagramSocket SrvSoc = new DatagramSocket(7777);
byte[] SData = new byte[1024];
System.out.println("Server Ready\n");
while (true)
{
byte[] RData = new byte[1024];
DatagramPacket RPack = new DatagramPacket(RData,
RData.length);
SrvSoc.receive(RPack);
String Text = new String(RPack.getData());
if (Text.trim().length() > 0)
{
System.out.println("From Client <<< " + Text);
InetAddress IPAddr = RPack.getAddress();
int Port = RPack.getPort();

37
SData = Text.toUpperCase().getBytes();
DatagramPacket SPack = new DatagramPacket(SData,
SData.length, IPAddr, Port);
SrvSoc.send(SPack);
}
else
break;
}
System.out.println("\nClient Quits\n");
SrvSoc.close();
}
}
UDPEchoClient
import java.io.*;
import java.net.*;
class UDPEchoClient
{
public static void main(String args[]) throws Exception
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
DatagramSocket CliSoc = new DatagramSocket();
InetAddress IPAddr;
String Text;
if (args.length == 0)
IPAddr = InetAddress.getLocalHost();
else
IPAddr = InetAddress.getByName(args[0]);
byte[] SData = new byte[1024];
System.out.println("To quit, press enter without text");
while (true)
{
System.out.print("\nEnter text for Server : ");
Text = br.readLine();
SData = Text.getBytes();
DatagramPacket SPack = new DatagramPacket(SData,
SData.length, IPAddr, 7777);
CliSoc.send(SPack);
if (Text.trim().length() == 0)
break;
byte[] RData = new byte[1024];
DatagramPacket RPack = new DatagramPacket(RData,
RData.length);
CliSoc.receive(RPack);
String Echo = new String(RPack.getData()) ;
Echo = Echo.trim();

38
System.out.println("Echo from Server <<< " + Echo);
}
CliSoc.close();
}
}
Output:

UDPEchoServer

UDPEchoClient

39
Result
Thus data from client to server is echoed in upper case to the client to check reliability of
the channel.
Ex. No. 9 (c) UDP DNS Server/Client
Date:

Aim:

To implement a DNS server and client in java using UDP sockets.

Algorithm:

UDPDNSServer

1. Define an array of hosts and its corresponding IP address in another array.


2. Create a datagram socket.
3. Create a datagram packet to receive client request.
4. Read the domain name from client to be resolved.
5. Lookup the host array for the domain name.
6. If found then retrieve corresponding address.
7. Construct a datagram packet to send response back to the client.
8. Repeat steps 3-7 to resolve further requests from clients.
9. Close the server socket.
10. Stop.
UDPDNSClient
1. Create a datagram socket.
2. Get domain name from user.
3. Construct a datagram packet to send domain name to the server.
4. Create a datagram packet to receive server message.
5. If it contains IP address then display it, else display "Domain does not exist".
6. Close the client socket.
7. Stop.

Program:

UDPDNSServer

import java.io.*;
import java.net.*;
public class UDPDNSServer
{
private static int indexOf(String[] array, String str)
{
str = str.trim();
for (int i=0; i < array.length; i++)

40
{
if (array[i].equals(str))
return i;
}
return -1;
}
public static void main(String arg[])throws IOException
{
String[] hosts = {"yahoo.com", "gmail.com","cricinfo.com", "facebook.com"};
String[] ip = {"68.180.206.184", "209.85.148.19","80.168.92.140", "69.63.189.16"};
System.out.println("Press Ctrl + C to Quit");
while (true)
{
DatagramSocket serversocket=new DatagramSocket(1362);
byte[] senddata = new byte[1021];
byte[] receivedata = new byte[1021];
DatagramPacket recvpack = new DatagramPacket(receivedata, receivedata.length);
serversocket.receive(recvpack);
String sen = new String(recvpack.getData());
InetAddress ipaddress = recvpack.getAddress();
int port = recvpack.getPort();
String capsent;
System.out.println("Request for host " + sen);
if(indexOf (hosts, sen) != -1)
capsent = ip[indexOf (hosts, sen)];
else
capsent = "Host Not Found";
senddata = capsent.getBytes();
DatagramPacket pack = new DatagramPacket (senddata, senddata. length, ipaddress, port);
serversocket.send(pack);
serversocket.close();
}
}
}
UDPDNSClient

import java.io.*;
import java.net.*;
public class UDPDNSClient
{
public static void main(String args[])throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
DatagramSocket clientsocket = new DatagramSocket();
InetAddress ipaddress;

41
if (args.length == 0)
ipaddress = InetAddress.getLocalHost();
else
ipaddress = InetAddress.getByName(args[0]);
byte[] senddata = new byte[1024];
byte[] receivedata = new byte[1024];
int portaddr = 1362;
System.out.print("Enter the hostname : ");
String sentence = br.readLine();
Senddata = sentence.getBytes();
DatagramPacket pack = new DatagramPacket(senddata,senddata.length,ipaddress, portaddr);
clientsocket.send(pack);
DatagramPacket recvpack =new DatagramPacket(receivedata,receivedata.length);
clientsocket.receive(recvpack);
String modified = new String(recvpack.getData());
System.out.println("IP Address: " + modified);
clientsocket.close();
}
}

Output:
UDPDNSServer

42
UDPDNSClient

Result

Thus domain name requests by the client are resolved into their respective logical address
using lookup method.

43
Ex. No. 10 Study Of Network Simulator (NS) and Simulation Of Congestion
Control Algorithms Using NS
Date:

Aim:
To Study of Network simulator (NS).and Simulation of Congestion Control Algorithms
using NS.

NETWORK SIMULATOR (NS2)


Ns overview
Ns programming: A Quick start.
Case study I: A simple Wireless network.
Case study II: Create a new agent in Ns.

Ns overview
Ns Status
Periodical release (ns-2.26, Feb 2003)
Platform support
FreeBSD, Linux, Solaris, Windows and Mac

Ns functionalities
Routing, Transportation, Traffic sources, queuing disciplines, QoS

Wireless
Ad hoc routing, mobile IP, sensor-MAC Tracing, visualization and various utilities NS
(Network Simulators) Most of the commercial simulators are GUI driven, while some network
simulators are CLI driven. The network model / configuration describe the state of the network
(nodes, routers, switches, links) and the events (data transmissions, packet error etc.). An
important output of simulations are the trace files. Trace files log every packet, every event that
occurred in the simulation and are used for analysis. Network simulators can also provide other
tools to facilitate visual analysis of trends and potential trouble spots.
Most network simulators use discrete event simulation, in which a list of pending
"events" is stored, and those events are processed in order, with some events triggering future
events—such as the event of the arrival of a packet at one node triggering the event of the arrival
of that packet at a downstream node.
Simulation of networks is a very complex task. For example, if congestion is high, then
estimation of the average occupancy is challenging because of high variance. To estimate the
likelihood of a buffer overflow in a network, the time required for an accurate answer can be
extremely large. Specialized techniques such as "control variates" and "importance sampling"
have been developed to speed simulation.
Examples of network simulators

44
There are many both free/open-source and proprietary network simulators. Examples of
notable network simulation software are, ordered after how often they are mentioned in research
papers:
1. ns (open source)
2. OPNET (proprietary software)
3. NetSim (proprietary software)
Uses of network simulators
Network simulators serve a variety of needs. Compared to the cost and time involved in
setting up an entire test bed containing multiple networked computers, routers and data links,
network simulators are relatively fast and inexpensive. They allow engineers, researchers to test
scenarios that might be particularly difficult or expensive to emulate using real hardware - for
instance, simulating a scenario with several nodes or experimenting with a new protocol in the
network. Network simulators are particularly useful in allowing researchers to test new
networking protocols or changes to existing protocols in a controlled and reproducible
environment. A typical network simulator encompasses a wide range of networking technologies
and can help the users to build complex networks from basic building blocks such as a variety of
nodes and links. With the help of simulators, one can design hierarchical networks using various
types of nodes like computers, hubs, bridges, routers, switches, links, mobile units etc.
Various types of Wide Area Network (WAN) technologies like TCP, ATM, IP etc. and
Local Area Network (LAN) technologies like Ethernet, token rings etc., can all be simulated with
a typical simulator and the user can test, analyze various standard results apart from devising
some novel protocol or strategy for routing etc. Network simulators are also widely used to
simulate battlefield networks in Network-centric warfare
There are a wide variety of network simulators, ranging from the very simple to the very
complex. Minimally, a network simulator must enable a user to represent a network topology,
specifying the nodes on the network, the links between those nodes and the traffic between the
nodes. More complicated systems may allow the user to specify everything about the protocols
used to handle traffic in a network. Graphical applications allow users to easily visualize the
workings of their simulated environment. Text-based applications may provide a less intuitive
interface, but may permit more advanced forms of customization.
Packet loss
occurs when one or morepacketsof data travelling across a computer networkfail to
reachtheir destination. Packet loss is distinguished as one of the three main error types
encountered in digital communications; the other two being bit errorand spurious packets caused
due to noise.
Packets can be lost in a network because they may be dropped when a queue in the
network node overflows. The amount of packet loss during the steady state is another important
property of a congestion control scheme. The larger the value of packet loss, the more difficult it
is for transportlayer protocols to maintain high bandwidths, the sensitivity to loss of individual
packets, as well as to frequency and patterns of loss among longer packet sequences is strongly
dependent on the application itself.
Throughput
This is the main performance measure characteristic, and most widely used.
Incommunicationnetworks, such asEthernetorpacket radio, throughputor network throughputis
the average rate of successfulmessage delivery over a communication channel. The throughput is
usually measured inbitsper second (bit/s orbps), andsometimes indata packetsper second or data

45
packets pertime slotThis measure how soon the receiver is able to get a certain amount of data
send by the sender. It is determined as the ratio of the total data received to the end to end delay.
Throughput is an important factor which directly impacts the network performance
Delay
Delay is the time elapsed while a packet travels from one point e.g., source premise or
network ingress to destination premise or network degrees. The larger the valueof delay, the
more difficult it is for transport layer protocols to maintain highbandwidths. We will calculate
end to end delay
Queue Length
A queuing system in networks can be described as packets arriving for service, waiting
for service if it is not immediate, and if having waited for service, leaving thesystem after being
served. Thus queue length is very important characteristic to determine that how well the active
queue management of the congestion control
algorithm has been working.

Overview of TCP’s congestion control


TCP implements a window based flow control mechanism, as explained in [APS99].
Roughly speaking, a window based protocol means that the so called current window size
defines a strict upper bound on the amount of unacknowledged data that can be in transit
between a given sender receiver pair. Originally TCP’s flow control was governed simply by the
maximum allowed window size advertised by the receiver and the policy that allowed the sender
to send new packets only after receiving the acknowledgement for the previous packet.
After the occurrence of the so called congestion collapse in the Internet in the late 80’s it
was realised, however, that special congestion control algorithms would be required to prevent
the TCP senders from overrunning the resources of the network. In 1988, Tahoe TCP was
released including three congestion control algorithms: slow start, congestion avoidance and fast
retransmit. In 1990 Reno TCP, providing one more algorithm called fast recovery, was released.
Besides the receiver’s advertised window, awnd, TCP’s congestion control introduced
two new variables for the connection: the congestion window, cwnd, and the slowstart threshold,
ssthresh.
The window size of the sender, w, was defined to be w = min(cwnd, awnd), instead of
being equal to awnd. The congestion window can be thought of as being a counterpart to
advertised window. Whereas awnd is used to prevent the sender from overrunning the resources
of the receiver, the purpose of cwnd is to prevent the sender from sending more data than the
network can accommodate in the current load conditions.
The idea is to modify cwnd adaptively to reflect the current load of the network. In
practice, this is done through detection of lost packets. A packet loss can basically be detected
either via a time-out mechanism or via duplicate ACKs.

Timeouts: Associated with each packet is a timer. If it expires, timeout occurs, and the packet is
retransmitted. The value of the timer, denoted by RTO, should ideally be of the order of an RTT.
However, as the value of RTT is not known in practice, it is measured by the TCP connection by
using, e.g, the so called Karn algorithm.

46
Duplicate ACKs: If a packet has been lost, the receiver keeps sending acknowledgements but
does not modify the sequence number field in the ACK packets. When the sender observes
several ACKs acknowledging the same packet, it concludes that a packet has been lost.
1. Slow start and congestion avoidance
In slow start, when a connection is established, the value of cwnd is first set to 1 and after
each received ACK the value is updated to
cwnd = cwnd + 1 implying doubling of cwnd for each RTT.
The exponential growth of cwnd continues until a packet loss is observed, causing the
value of ssthresh to be updated to
ssthresh = cwnd/2.
After the packet loss, the connection starts from slow start again with cwnd = 1, and the
window is increased exponentially until it equals ssthresh, the estimate for the available
bandwidth in the network. At this point, the connection goes to congestion avoidance phase
where the value of cwnd is increased less aggressively with the pattern
cwnd = cwnd + 1/cwnd, implying linear instead of exponential growth. This linear
increase will continue until a packet loss is detected.

2. Fast Retransmit
Duplicate ACKs that were mentioned to be one way of detecting lost packets can also be
caused by reordered packets. When receiving one duplicate ACK the sender cannot yet know
whether the packet has been lost or just gotten out of order but after receiving several duplicate
ACKs it is reasonable to assume that a packet loss has occurred. The purpose of fast retransmit
mechanism is to speed up the retransmission process by allowing the sender to retransmit a
packet as soon as it has enough evidence that a packet has been lost. This means that instead of
waiting for the retransmit timer to expire, the sender can retransmit a packet immediately after
receiving three duplicate ACKs.

3. Fast Recovery
In Tahoe TCP the connection always goes to slow start after a packet loss. However, if
the window size is large and packet losses are rare, it would be better for the connection to
continue from the congestion avoidance phase, since it will take a while to increase the window
size from 1 to ssthresh. The purpose of the fast recovery algorithm in Reno TCP is to achieve this
behaviour.
In a connection with fast retransmit, the source can use the flow of duplicate ACKs to
clock the transmission of packets. When a possibly lost packet is retransmitted, the values of
ssthresh and cwnd will be set to
ssthresh = cwnd/2 and cwnd = ssthresh meaning that the connection will continue from
the congestion avoidance phase and increases its window size linearly.

Causing of Congestion:
The various causes of congestion in a subnet are:
1. The input traffic rate exceeds the capacity of the output lines. If suddenly, a stream of packet
start arriving on three or four input lines and all need the same output line. In this case, a queue
will be built up. If there is insufficient memory to hold all the packets, the packet will be lost.
Increasing the memory to unlimited size does not solve the problem. This is because, by the time
packets reach front of the queue, they have already timed out (as they waited the queue). When

47
timer goes off source transmits duplicate packet that are also added to the queue. Thus same
packets are added again and again, increasing the load all the way to the destination.

2. The routers are too slow to perform bookkeeping tasks (queuing buffers, updating tables, etc.).
3. The routers' buffer is too limited.
4. Congestion in a subnet can occur if the processors are slow. Slow speed CPU at routers will
perform the routine tasks such as queuing buffers, updating table etc slowly. As a result of this,
queues are built up even though there is excess line capacity.
5. Congestion is also caused by slow links. This problem will be solved when high speed links
are used. But it is not always the case. Sometimes increase in link bandwidth can further
deteriorate the congestion problem as higher speed links may make the network more
unbalanced. Congestion can make itself worse. If a route!" does not have free buffers, it starts
ignoring/discarding the newly arriving packets. When these packets are discarded, the sender
may retransmit them after the timer goes off. Such packets are transmitted by the sender again
and again until the source gets the acknowledgement of these packets. Therefore multiple
transmissions of packets will force the congestion to take place at the sending end.

How to correct the Congestion Problem:


Congestion Control refers to techniques and mechanisms that can either prevent
congestion, before it happens, or remove congestion, after it has happened. Congestion control
mechanisms are divided into two categories, one category prevents the congestion from
happening and the other category removes congestion after it has taken place.

These two categories are:

48
1. Open loop
2. Closed loop
Open Loop Congestion Control
• In this method, policies are used to prevent the congestion before it happens.
• Congestion control is handled either by the source or by the destination.
• The various methods used for open loop congestion control are:
1. Retransmission Policy
• The sender retransmits a packet, if it feels that the packet it has sent is lost or corrupted.
• However retransmission in general may increase the congestion in the network. But we need to
implement good retransmission policy to prevent congestion.
• The retransmission policy and the retransmission timers need to be designed to optimize
efficiency and at the same time prevent the congestion.
2. Window Policy
• To implement window policy, selective reject window method is used for congestion control.
• Selective Reject method is preferred over Go-back-n window as in Go-back-n method, when
timer for a packet times out, several packets are resent, although some may have arrived safely at
the receiver. Thus, this duplication may make congestion worse.
• Selective reject method sends only the specific lost or damaged packets.
3. Acknowledgement Policy
• The acknowledgement policy imposed by the receiver may also affect congestion.
• If the receiver does not acknowledge every packet it receives it may slow down the sender and
help prevent congestion.
• Acknowledgments also add to the traffic load on the network. Thus, by sending fewer
acknowledgements we can reduce load on the network.
• To implement it, several approaches can be used:
1. A receiver may send an acknowledgement only if it has a packet to be sent.
2. A receiver may send an acknowledgement when a timer expires.
3. A receiver may also decide to acknowledge only N packets at a time.
4. Discarding Policy
• A router may discard less sensitive packets when congestion is likely to happen.
• Such a discarding policy may prevent congestion and at the same time may not harm the
integrity of the transmission.
5. Admission Policy
• An admission policy, which is a quality-of-service mechanism, can also prevent congestion in
virtual circuit networks.
• Switches in a flow first check the resource requirement of a flow before admitting it to the
network.
• A router can deny establishing a virtual circuit connection if there is congestion in the "network
or if there is a possibility of future congestion.
Closed Loop Congestion Control
• Closed loop congestion control mechanisms try to remove the congestion after it happens.
• The various methods used for closed loop congestion control are:
1. Backpressure
• Backpressure is a node-to-node congestion control that starts with a node and propagates, in the
opposite direction of data flow.

49
• The backpressure technique can be applied only to virtual circuit networks. In such virtual
circuit each node knows the upstream node from which a data flow is coming.
• In this method of congestion control, the congested node stops receiving data from the
immediate upstream node or nodes.
• This may cause the upstream node on nodes to become congested, and they, in turn, reject data
from their upstream node or nodes.
• As shown in fig node 3 is congested and it stops receiving packets and informs its upstream
node 2 to slow down. Node 2 in turns may be congested and informs node 1 to slow down. Now
node 1 may create congestion and informs the source node to slow down. In this way the
congestion is alleviated. Thus, the pressure on node 3 is moved backward to the source to
remove the congestion.
2. Choke Packet
• In this method of congestion control, congested router or node sends a special type of packet
called choke packet to the source to inform it about the congestion.
• Here, congested node does not inform its upstream node about the congestion as in
backpressure method.
• In choke packet method, congested node sends a warning directly to the source station i.e. the
intermediate nodes through which the packet has traveled are not warned.

3. Implicit Signaling
• In implicit signaling, there is no communication between the congested node or nodes and the
source.
• The source guesses that there is congestion somewhere in the network when it does not receive
any acknowledgment. Therefore the delay in receiving an acknowledgment is interpreted as
congestion in the network.
• On sensing this congestion, the source slows down.
• This type of congestion control policy is used by TCP.
4. Explicit Signaling
• In this method, the congested nodes explicitly send a signal to the source or destination to
inform about the congestion.

50
• Explicit signaling is different from the choke packet method. In choke packed method, a
separate packet is used for this purpose whereas in explicit signaling method, the signal is
included in the packets that carry data .
• Explicit signaling can occur in either the forward direction or the backward direction .
• In backward signaling, a bit is set in a packet moving in the direction opposite to the
congestion. This bit warns the source about the congestion and informs the source to slow down.
• In forward signaling, a bit is set in a packet moving in the direction of congestion. This bit
warns the destination about the congestion. The receiver in this case uses policies such as
slowing down the acknowledgements to remove the congestion.
Congestion control algorithms
1. Leaky Bucket Algorithm
• It is a traffic shaping mechanism that controls the amount and the rate of the traffic sent to the
network.
• A leaky bucket algorithm shapes bursty traffic into fixed rate traffic by averaging the data rate.
• Imagine a bucket with a small hole at the bottom.
• The rate at which the water is poured into the bucket is not fixed and can vary but it leaks from
the bucket at a constant rate. Thus (as long as water is present in bucket), the rate at which the
water leaks does not depend on the rate at which the water is input to the bucket.

• Also, when the bucket is full, any additional water that enters into the bucket spills over the
sides and is lost.
• The same concept can be applied to packets in the network. Consider that data is coming from
the source at variable speeds. Suppose that a source sends data at 12 Mbps for 4 seconds. Then
there is no data for 3 seconds. The source again transmits data at a rate of 10 Mbps for 2 seconds.
Thus, in a time span of 9 seconds, 68 Mb data has been transmitted.
If a leaky bucket algorithm is used, the data flow will be 8 Mbps for 9 seconds. Thus constant
flow is maintained.

51
2. Token bucket Algorithm
• The leaky bucket algorithm allows only an average (constant) rate of data flow. Its major
problem is that it cannot deal with bursty data.
• A leaky bucket algorithm does not consider the idle time of the host. For example, if the host
was idle for 10 seconds and now it is willing to sent data at a very high speed for another 10
seconds, the total data transmission will be divided into 20 seconds and average data rate will be
maintained. The host is having no advantage of sitting idle for 10 seconds.
• To overcome this problem, a token bucket algorithm is used. A token bucket algorithm allows
bursty data transfers.
• A token bucket algorithm is a modification of leaky bucket in which leaky bucket contains
tokens.
• In this algorithm, a token(s) are generated at every clock tick. For a packet to be transmitted,
system must remove token(s) from the bucket.
• Thus, a token bucket algorithm allows idle hosts to accumulate credit for the future in form of
tokens.
• For example, if a system generates 100 tokens in one clock tick and the host is idle for 100
ticks. The bucket will contain 10,000 tokens.
Now, if the host wants to send bursty data, it can consume all 10,000 tokens at once for sending
10,000 cells or bytes.
Thus a host can send bursty data as long as bucket is not empty.

52
RESULT
Thus the study of Network simulator (NS2) was studied

53