0% found this document useful (0 votes)
17 views92 pages

Lab Mannual

The Networking Lab Manual for CSL 332 outlines the objectives and activities for students in the Computer Science and Engineering department at Sree Buddha College of Engineering for the academic year 2022-23. It includes two cycles of lab exercises focusing on network configuration, socket programming, routing protocols, and system calls in Linux. The manual provides detailed instructions on various networking commands and system calls essential for network programming.

Uploaded by

nivedb02
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views92 pages

Lab Mannual

The Networking Lab Manual for CSL 332 outlines the objectives and activities for students in the Computer Science and Engineering department at Sree Buddha College of Engineering for the academic year 2022-23. It includes two cycles of lab exercises focusing on network configuration, socket programming, routing protocols, and system calls in Linux. The manual provides detailed instructions on various networking commands and system calls essential for network programming.

Uploaded by

nivedb02
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 92

Lab Manual

CSL 332

Networking Lab

ACADEMIC YEAR :2022-23


PREPARED BY:Ms.Dhanya Sreedharan(Asst Prof)
Ms.Minumol E M (Lab Instructor)

VERIFIED BY:Dr S V Annlin Jeba(HoD,CSE)

Department of Computer Science and Engineering,


Sree Buddha College of Engineering ,Pattoor

Networking Lab Manual Dept of CSE


SREE BUDDHA COLLEGE OF ENGINEERING PATTOOR
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
CSL 332 NETWORKING LAB
LAB CYCLE

CYCLE I

1. To familiarize network configuration files and networking commands in Linux.


2. To familiarize and understand the use and functioning of system calls used for network
programming in Linux.
3. To implement client-server communication using socket programming and TCP as
transport layer protocol.
4. To implement client-server communication using socket programming and UDP as
transport layer protocol .
5. To implement sliding window flow control protocol Stop and Wait.
6. To implement sliding window flow control protocol Go back N.
7. To implement sliding window flow control protocol Selective Repeat ARQ protocol.

CYCLE II

8. To implement and simulate algorithm for Distance Vector Routing protocol .


9. To implement and simulate algorithm for Link State Routing protocol.
10. To implement Simple Mail Transfer Protocol.
11. To implement File Transfer Protocol.
12. To implement congestion control using a leaky bucket algorithm.
13. To understand the Wireshark tool.

Networking Lab Manual Dept of CSE


Program 1

Getting started with Basics of Network configurations files and Networking


Commands in Linux.

The important network configuration files in Linux operating systems are

1. /etc/hosts

This file is used to resolve hostnames on small networks with no DNS server. This text file contains
a mapping of an IP address to the corresponding host name in each line. This file also contains a line
specifying the IP address of the loopback device i.e, 127.0.0.1 is mapped to localhost.
A typical hosts file is as shown

127.0.0.1 localhost

127.0.1.1 anil-300E4Z-300E5Z-300E7Z

2. /etc/resolv.conf

This configuration file contains the IP addresses of DNS servers and the search domain.

A sample file is shown

# DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN

nameserver 127.0.1.1

3. /etc/sysconfig/network

This configuration file specifies routing and host information for all network interfaces. It contains
directives that are global specific. For example if NETWORKING=yes, then /etc/init.d/network
activates network devices.

4. /etc/nsswitch.conf

This file includes database search entries. The directive specifies which database is to be searched first.
The important Linux networking commands are

Networking Lab Manual Dept of CSE


1. ifconfig

This command gives the configuration of all interfaces in the system.


It can be run with an interface name to get the details of the interface.
ifconfig wlan0
Link encap:Ethernet HWaddr b8:03:05:ad:6b:23

inet addr:192.168.43.15 Bcast:192.168.43.255 Mask:255.255.255.0

inet6 addr: 2405:204:d206:d3b1:ba03:5ff:fead:6b23/64 Scope:Global


inet6 addr: fe80::ba03:5ff:fead:6b23/64 Scope:Link
inet6 addr: 2405:204:d206:d3b1:21ee:5665:de59:bd4e/64 Scope:Global
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:827087 errors:0 dropped:0 overruns:0 frame:0
TX packets:433391 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:1117797710 (1.1 GB) TX bytes:53252386 (53.2 MB)

This gives the IP address, subnet mask, and broadcast address of the wireless LAN adapter.
Also tells that it can support multicasting.

If eth0 is given as the parameter, the command gives the details of the Ethernet adapter.

2. netstat

This command command gives network status information.

Netstat -i

Networking Lab Manual Dept of CSE


Iface MTU Met RX-OK RX-ERR RX-DRP RX-OVR TX-OK TX-ERR TX-DRP TX-OVR Flg

eth0 1500 0 0 0 0 0 0 0 0 0 BMU

lo 65536 0 12166 0 0 0 12166 0 0 0 LRU

wlan0 1500 0 827946 0 0 0 434246 0 0 0 BMRU

As shown above, the command with -i flag provides information on the interfaces. lo stands for
loopback interface.

3. ping

This is the most commonly used command for checking connectivity.

ping www.google.com

PING www.google.com (172.217.163.36) 56(84) bytes of data.

64 bytes from maa05s01-in-f4.1e100.net (172.217.163.36): icmp_seq=1 ttl=53 time=51.4 ms


64 bytes from maa05s01-in-f4.1e100.net (172.217.163.36): icmp_seq=2 ttl=53 time=50.3 ms
64 bytes from maa05s01-in-f4.1e100.net (172.217.163.36): icmp_seq=3 ttl=53 time=48.5 ms
64 bytes from maa05s01-in-f4.1e100.net (172.217.163.36): icmp_seq=4 ttl=53 time=59.8 ms
64 bytes from maa05s01-in-f4.1e100.net (172.217.163.36): icmp_seq=5 ttl=53 time=57.8 ms
64 bytes from maa05s01-in-f4.1e100.net (172.217.163.36): icmp_seq=6 ttl=53 time=59.2 ms
64 bytes from maa05s01-in-f4.1e100.net (172.217.163.36): icmp_seq=7 ttl=53 time=68.2 ms
64 bytes from maa05s01-in-f4.1e100.net (172.217.163.36): icmp_seq=8 ttl=53 time=58.8 ms
^C

--- www.google.com ping statistics ---

8 packets transmitted, 8 received, 0% packet loss, time 7004ms


rtt min/avg/max/mdev = 48.533/56.804/68.266/6.030 ms

A healthy connection is determined by a steady stream of replies with consistent times. Packet loss is
shown by discontinuity of sequence numbers. Large scale packet loss indicates problem along the
path.

Networking Lab Manual Dept of CSE


Program2

Aim

To familiarize and understand the use and functioning of System Calls used for
Operating system and network programming in Linux.
Some system calls of Linux operating systems

1. ps

This command tells which all processes are running on the system when ps runs.
ps -ef
UID PID PPID C STIME TTY TIME CMD

root 1 0 0 13:55 ? 00:00:01 /sbin/init

root 2 0 0 13:55 ? 00:00:00 [kthreadd]

root 3 2 0 13:55 ? 00:00:00 [ksoftirqd/0]

root 4 2 0 13:55 ? 00:00:01 [kworker/0:0]

root 5 2 0 13:55 ? 00:00:00 [kworker/0:0H]

root 7 2 0 13:55 ? 00:00:00 [rcu_sched]

root 8 2 0 13:55 ? 00:00:00 [rcuos/0]

This command gives processes running on the system, the owners of the processes and the names of
the processes. The above result is an abridged version of the output.

2. fork

This system call is used to create a new process. When a process makes a fork system call, a new process
is created which is identical to the process creating it. The process which calls fork is calledthe parent
process and the process that is created is called the child process. The child and parent processes are
identical, i.e, child gets a copy of the parent's data space, heap and stack, but have different physical
address spaces. Both processes start execution from the line next to fork. Fork returns the process id of
the child in the parent process and returns 0 in the child process.

Networking Lab Manual Dept of CSE


#include<stdio.h>
void main()
{

int pid;

pid = fork();
if(pid > 0)
{

printf (“ Iam parent\n”);

else

printf(“Iam child\n”);

The parent process prints the first statement and the child prints the next statement.

3. exec

New programs can be run using exec system call. When a process calls exec, the process is completely
replaced by the new program. The new program starts executing from its main function.
A new process is not created, process id remains the same, and the current process's text, data, heap, and
stack segments are replaced by the new program. exec has many flavours one of which is execv.
execv takes two parameters. The first is the pathname of the program that is going to be executed. The
second is a pointer to an array of pointers that hold the addresses of arguments. These arguments are the
command line arguments for the new program.

4. wait

When a process terminates, its parent should receive some information reagarding the process like the
process id, the termination status, amount of CPU time taken etc. This is possible only if the parent
process waits for the termination of the child process. This waiting is done by calling the wait system
call. When the child process is running, the parent blocks when wait is called. If the child terminates
normally or abnormally, wait immedaitely returns with the termination status of the child. The wait
system call takes a parameter which is a pointer to a location in which the termination status is stored.

5. exit

Networking Lab Manual Dept of CSE


When exit function is called, the process undergoes a normal termination.

6. open

This system call is used to open a file whose pathname is given as the first parameter of the function.
The second parameter gives the options that tell the way in which the file can be used.
open(filepathname , O_RDWR);

This causes the file to be read or written. The function returns the file descriptor of the file.

7. read

This system call is used to read data from an open file.


read(fd, buffer, sizeof(buffer));
The above function reads sizeof(buffer) bytes into the array named buffer. If the end of file is
encountered, 0 is returned, else the number of bytes read is returned.

8. write

Data is written to an open file using write function.


write(fd, buffer, sizeof(buffer));
System calls for network programming in Linux

Socket():

To do network I/O, the first thing a process must do is to call the socket system call, specifying the type
of communication protocol desired.
#include <sys/types.h>
#include <sys/socket.h>

int socket(int family, int type, int protocol);

The family is one of


AF_UNIX -- Unix internal protocols
AF_INET -- Internet protocols
AF_NS -- Xerox NS Protocols
AF_IMPLINK -- IMP link layer

The AF_ prefix stands for "address family." In the first project, we are going to use AF_INET.

The socket type is one of the following:


SOCK_STREAM stream socket
SOCK_DGRAM datagram socket
SOCK_RAW raw socket
SOCK_SEQPACKET sequenced packet socket
SOCK_RDM reliably delivered message socket (not implemented yet)

The protocol argument to the socket system call is typically set to 0 for most user applications. The valid
combinations are shown as follows.
Actual
family type Protocol
protocol
AF_I SOCK_DGR IPPROTO_U
UDP
NET AM DP
Networking Lab Manual Dept of CSE
AF_I SOCK_STRE IPPROTO_T
TCP
NET AM CP
AF_I IPPROTO_I
SOCK_RAW ICMP
NET CMP
AF_I IPPROTO_R
SOCK_RAW (raw)
NET AW

bind()
The bind system call assigns a name to an unnamed socket.
#include <sys/types.h>
#include <sys/socket.h>

int bind(int sockfd, struct sockaddr *myaddr, int addrlen);

The first argument is the socket descriptor returned from socket system call. The second argument is a pointer to
a protocol-specific address and the third argument is the size of this address. There are three uses of bind.
1.Servers register their well-known address with the system. It tells the system "this is my address and any
messages received for this address are to be given to me." Both connection-oriented and connectionless servers
need to do this before accepting client requests.
2.A client can register a specific address for itself.
3.A connectionless client needs to assure that the system assigns it some unique address, so that the other end (the
server) has a valid return address to send its responses to. This corresponds to making certain an envelope has a
valid return address, if we expect to get a reply from the person we sent the letter to.

connect()
A client process connects a socket descriptor following the socket system call to establish a connection with a
server.
#include <sys/types.h>
#include <sys/socket.h>

int connect(int sockfd, struct sockaddr *servaddr, int addrlen);

The sockfd is a socket descriptor that was returned by the socket system call. The second and third arguments are
a pointer to a socket address, and its size.
For most connection-oriented protocols (TCP, for example), the connect system call results in the actual
establishment of a connection between the local system and the foreign system.
The connect system call does not return until the connection is established, or an error is returned to the process.
The client does not have to bind a local address before calling connect. The connection typically causes these
four elements of the association 5-tuple to be assigned:local-addr, local-process, foreign-addr, and foreign-
process.
listen()
This system call is used by a connection-oriented server to indicate that it is willing to receive connections.
#include <sys/types.h>
#include <sys/socket.h>

int listen(int sockfd, int backlog);

It is usually executed after both the socket and bind system calls, and immediately before the accept system call.
The backlog argument specifies how many connection requests can be queued by the system while it waits for
the server to execute the accept system call. This argument is usually specified as 5, the maximum value
currently allowed.

Networking Lab Manual Dept of CSE


accept()
After a connection-oriented server executes the listen system call described above, an actual connection from
some client process is waited for by having the server execute the accept system call.
#include <sys/types.h>
#include <sys/socket.h>

int accept(int sockfd, struct sockaddr *peer, int *addrlen);

accept takes the first connection request on the queue and creates another socket with the same properties as
sockfd. If there are no connection requests pending, this call blocks the caller until one arrives.
The peer and addrlen arguments are used to return the address of the connected peer process (the client).addrlen
is called a value-result argument: the caller sets its value before the system call, and the system call stores a
result in the variable. For this system call the caller sets addrlen to the size of the sockaddr structure whose
address is passed as the peer argument.
send, sendto, recv and recvfrom
These system calls are similar to the standard read and write system calls, but additional arguments are required.
#include <sys/types.h>
#include <sys/socket.h>

int send(int sockfd, char *buff, int nbytes, int flags);


int sendto(int sockfd, char *buff, int nbytes, int flags, struct sockaddr *to, int addrlen);
int recv(int sockfd, char *buff, int nbytes, int flags);
int recvfrom(int sockfd, char *buff, int nbytes, int flags, struct sockaddr *from, int *addrlen);

The first three arguments, sockfd, buff, and nbytes, to the four system calls are similar to the first three arguments
for read and write. The flags argument can be safely set to zero ignoring the details for it. The toargument
for sendto specifies the protocol-specific address of where the data is to be sent. Since this address is protocol-
specific, its length must be specified by addrlen. The recvfrom system call fills in the protocol-specific address
of who sent the data into from. The length of this address is also returned to the caller in addrlen. Note that the
final argument to sendto is an integer value, while the final argument to recvfrom is a pointer to an integer
value.
close
The normal Unix close system call is also used to close a socket.
int close(int fd);

Result
Familiarized various system calls used for network programming in Linux

Networking Lab Manual Dept of CSE


Experiment 3
Client-Server chat program using TCP
Aim

To write a C program for implementing client server chat using TCP .

Algorithm
Server
1. Start the program
2. Create an unnamed socket for the server using the parameters AF-INET as domain and the SOCK-STREAM as type.
3. Name the socket using bind() system call with the parameters server-sockfd and the server address(sin-addr and sin-
sport)
4. Create a connection queue and wait for which the cliets using the listen() system call with the number of client request
as parameters.
5. Get the client id as input from the user to communicate. If the client id is 0. Then go to step 10 otherwise go to step 6.
6. Accept the connection using acept() system call when client requests for connection.
7. Get the messages which has to be sent to the client and check that is not equal to “Bye’.
8. If the message is not equal to ‘Bye’ then write the message to the client and go to step6.
9. If the message is ‘Bye’ then terminate the connection with current client and goto step5.
10. Stop the program execution.
Client

1. Start the program


2. Create an unwanted socket for client using socket() system.
3. Call with parameters AF-INET as domain and SOCK-Stream as type.
4. Name the socket using bind() system call.
5. Now connect the socket to server using connect system call.
6. Read the message from the server socket amd compare it with ‘Bye’.
7. If the message is not equal to ‘bye’ , then print the message to the server output device and repeat the step 6 and 7.
8. Get the messages from the client side.
9. Write the message to server sockfd and goto step4.
10. If the message is equal to ‘Bye; then print goodbye message and terminate the process.
11. Stop the process.

Program
Server.c

#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#define PORT 2020
#define BACKLOG 2
main()

Networking Lab Manual Dept of CSE


{
int fd,fd1,sin_addr,sin_size,i=0;
char content[30];
struct sockaddr_in server,client;
if((fd=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))==-1)
{
printf("socket error");
exit(-1);
}
bzero((char*)&client,sizeof(server));
server.sin_family=AF_INET;
server.sin_port=htons(PORT);
server.sin_addr.s_addr=htonl(INADDR_ANY);
if(bind(fd,(struct sockaddr*)&server,sizeof(server))==-1)
{
printf("bind()error");
exit(-1);
}
if(listen(fd,BACKLOG)==-1)
{
printf("listen()error\n");
exit(-1);
}
printf("\n server is in listening mode");
sin_size=sizeof(client);
if((fd1=accept(fd,(struct sockaddr*)&client,&sin_size))==-1)
{
printf("accept error");
exit(-1);
}
printf("point to point communication,type EXIT to quit \n");
i=0;
if(!fork())
while(1)
{
i=recv(fd1,content,30,0);
Networking Lab Manual Dept of CSE
content[i]='\0';
printf("%s\n",content);
if(!strcmp(content,"EXIT"))
{
printf("client wants to close");
break;
}
}
else
while(1)
{
scanf("%s",content);
send(fd1,content,30,0);
if(!strcmp(content,"EXIT"))
{
printf("write mode on exit");
break;
}
}
close(fd);
close(fd1);

Client.c

#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#define PORT 2020
main()
{
int fd1,i;
Networking Lab Manual Dept of CSE
char content[30];
struct sockaddr_in client;
if((fd1=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))==-1)
{
printf("socket error");
exit(-1);
}
bzero(&client,sizeof(client));
client.sin_family=AF_INET;
client.sin_port=htons(PORT);
if(connect(fd1,(struct sockaddr*)&client,sizeof(client))==-1)
{
printf("connect error");
exit(-1);
}
printf("point to point communication,type EXIT to quit \n");
i=0;
if(!fork())
while(1)
{
i=recv(fd1,content,30,0);
content[i]='\0';
printf("%s\n",content);
if(!strcmp(content,"EXIT"))
{
break;
}
}
else
while(1)
{
scanf("%s",content);
send(fd1,content,30,0);
if(!strcmp(content,"EXIT"))
{
printf("write mode on exit");
Networking Lab Manual Dept of CSE
break;
}
}
close(fd1);

Output:

Server:

server is in listening modepoint to point communication,type EXIT to quit


hello
how are you
EXIT
write mode on exit

Client:

point to point communication,type EXIT to quit


hello
how
are
you
EXIT

Result

The program is executed successfully

Networking Lab Manual Dept of CSE


PROGRAM 4
Client-Server chat program using UDP
Aim
To write a C program for implementation of UDP sockets.

Algorithm
1. Enter the source and destination port number for both server and client.
2. Create an unnamed socket for the server.
3. Name the socket using bind() system call.
4. Using recvfrom() system call, server gets the message from the client.
5. Using sendto() system call, client deliver the message to the server.
6. If the message is ‘EXIT” then exit the program.
7. Stop the program.

Program

#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
main()
{
int fd,sin_size,p1,p2,i;
char buf[50];
struct sockaddr_in server,client;
printf("Enter the source and destination port no\n");
scanf("%d%d",&p1,&p2);
if((fd=socket(AF_INET,SOCK_DGRAM,0))==-1)
{
printf("socket error");
exit(-1);
}
bzero(&server,sizeof(server));
bzero(&client,sizeof(client));

Networking Lab Manual Dept of CSE


client.sin_family=AF_INET;
server.sin_family=AF_INET;
server.sin_port=htons(p1);
client.sin_port=htons(p2);
server.sin_addr.s_addr=htonl(INADDR_ANY);
client.sin_addr.s_addr=htonl(INADDR_ANY);
if(bind(fd,(struct sockaddr*)&server,sizeof(server))==-1)
{
printf("bind error\n");
exit(-1);
}
sin_size=sizeof(client);
while(1)
{
if(!fork())
while(1)
{
recvfrom(fd,buf,100,0,(struct sockaddr*)&client,&sin_size);
printf("%s\n",buf);
break;
}
else
while(1)
{
scanf("%s",buf);
sendto(fd,buf,100,0,(struct sockaddr*)&client,sin_size);
break;
}
if(strcmp(buf,"EXIT")==0)
break;
}
close(fd);
return 0;
}

Output
Networking Lab Manual Dept of CSE
Server

Enter the source and destination port no


6523
5892
hello
hai

Client

Enter the source and destination port no


6523
5892
hello
hai

Result

The program is executed successfully

Networking Lab Manual Dept of CSE


PROGRAM 5
SLIDING WINDOW FLOW CONTROL PROTOCOLS

Aim:-To write a program to simulate stop – and – wait protocol.

Description of Stop-and-Wait Protocol

Stop-and-wait Protocol is a flow control protocol used in the data link layer for ansmission of data in
noiseless channels. Sender keeps on sending messages to the Receiver. In order to prevent the receiver
from overwhelming, there is a need to tell the sender to slow down the transmission of frames. We can
make use of feedback from the receiver to the sender. Frames 0 sends to receiver, ACK 1 will be
sentback to sender; frame 1 goes to receiver, ACK 0 will be back to sender, and so on.

Algorithm

1. Start the program

2. Generate a random number that gives the total number of frames to be transmitted.

3. Transmit the first frame

4. Receive the acknowledgement for the first frame

5. Transmit the next frame

6. Find the remaining frames to be sent.

7. If an acknowledgement is not received for a particular frame, retransmit that frame alone again.

8. Repeat the steps 5 to 7 till the number of remaining frames to be sent becomes zero.

9. Stop the program.

Networking Lab Manual Dept of CSE


Code –

#include<stdio.h>

#include<stdlib.h>

Networking Lab Manual Dept of CSE


#include<unistd.h>

int main()

int i,j,noframes,x,x1=10,x2;

for(i=0;i<200;i++)

rand();

noframes=rand()/200;

i=1;

j=1;

noframes = noframes / 8;

printf("\n number of frames is %d",noframes);

while(noframes>0)

printf("\nsending frame %d",i);

srand(x1++); //The srand() function sets the starting point for producing a series of pseudo-random
integers

x = rand()%10;

if(x%2 == 0)

for (x2=1; x2<2; x2++)

printf("waiting for %d seconds\n", x2);

sleep(x2);

printf("Missing Acknowledgement %d",i);

Networking Lab Manual Dept of CSE


printf("\nsending frame %d",i);

srand(x1++);

x = rand()%10;

printf("\nack received for frame %d",j);

noframes-=1;

i++;

j++;

printf("\n end of stop and wait protocol");

Output

number of frames is 1314574

sending frame 1

ack received for frame 1

sending frame 2

ack received for frame 2

sending frame 3waiting for 1 seconds

Missing Acknowledgement 3

sending frame 3

ack received for frame 3

sending frame 4

ack received for frame 4

sending frame 5

ack received for frame 5


Networking Lab Manual Dept of CSE
sending frame 6waiting for 1 seconds

Missing Acknowledgement 6

sending frame 6

ack received for frame 6

sending frame 7waiting for 1 seconds

Missing Acknowledgement 7

sending frame 7

ack received for frame 7

sending frame 8

ack received for frame 8

sending frame 9waiting for 1 seconds

Missing Acknowledgement 9

sending frame 9

ack received for frame 9

sending frame 10waiting for 1 seconds

Missing Acknowledgement 10

sending frame 10

ack received for frame 10

Algorithms for both Sender and Receiver sides

The algorithm used at the sender site for the stop-and-wait protocol

This is an algorithm used at the sender site for the stop-and-wait protocol. Applications can have its
implementation in its own programming language.

while(true) //Repeat forever

canSend=true //It will allow the first frame to go.

Networking Lab Manual Dept of CSE


{

WaitForEvent(); //sleep until the occurrence of an event

if(Event(RequestToSend) AND canSend) {

GetData();

MakeFrame();

SendFrame(); //Send the data frame

canSend=false; //cannot send until the acknowledgement arrives.

WaitForEvent(); //sleep until the occurrence of an event

if(Event(ArrivalNotification)) //indicates the arrival of the


acknowledgement

ReceiveFrame(); //Means the ACK frame received

canSend=true;

Algorithm At the Receiver Side

This is an algorithm used at the receiver side for the stop-and-wait protocol. Applications can have
their implementation in their own programming language.

while(true) //means Repeat forever

WaitForEvent(); //sleep until the occurrence of an event

if(Event(ArrivalNotification)) //indicates arrival of the data frame

Networking Lab Manual Dept of CSE


{

ReceiveFrame();

ExtractData();

Deliver(data); //delivers the data to the network layer.

SendFrame(); //Send the ACK frame

Networking Lab Manual Dept of CSE


CLIENT SIDE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

typedef struct packet{


char data[1024];
}Packet;

typedef struct frame{


int frame_kind; //ACK:0, SEQ:1 FIN:2
int sq_no;
int ack;
Packet packet;
}Frame;

int main(int argc, char **argv[]){


if (argc != 2){
printf("Usage: %s <port>", argv[0]);
exit(0);
}

int port = atoi(argv[1]);


int sockfd;
struct sockaddr_in serverAddr;
Networking Lab Manual Dept of CSE
char buffer[1024];
socklen_t addr_size;

int frame_id = 0;
Frame frame_send;
Frame frame_recv;
int ack_recv = 1;

sockfd = socket(AF_INET, SOCK_DGRAM, 0);

memset(&serverAddr, '\0', sizeof(serverAddr));


serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(port);
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");

while(1){

if(ack_recv == 1){
frame_send.sq_no = frame_id;
frame_send.frame_kind = 1;
frame_send.ack = 0;

printf("Enter Data: ");


scanf("%s", buffer);
strcpy(frame_send.packet.data, buffer);
sendto(sockfd, &frame_send, sizeof(Frame), 0, (struct sockaddr*)&serverAddr,
sizeof(serverAddr));
printf("[+]Frame Send\n");
}
int addr_size = sizeof(serverAddr);
int f_recv_size = recvfrom(sockfd, &frame_recv, sizeof(frame_recv), 0 ,(struct
sockaddr*)&serverAddr, &addr_size);

if( f_recv_size > 0 && frame_recv.sq_no == 0 && frame_recv.ack == frame_id+1){


printf("[+]Ack Received\n");
ack_recv = 1;
}else{
printf("[-]Ack Not Received\n");
ack_recv = 0;
}
frame_id++;
}
close(sockfd);
return 0;
}
Server Side
#include <stdio.h>
Networking Lab Manual Dept of CSE
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>

typedef struct packet{


char data[1024];
}Packet;

typedef struct frame{


int frame_kind; //ACK:0, SEQ:1 FIN:2
int sq_no;
int ack;
Packet packet;
}Frame;

int main(int argc, char** argv){

if (argc != 2){
printf("Usage: %s <port>", argv[0]);
exit(0);
}

int port = atoi(argv[1]);


int sockfd;
struct sockaddr_in serverAddr, newAddr;
char buffer[1024];
socklen_t addr_size;

int frame_id=0;
Frame frame_recv;
Frame frame_send;

sockfd = socket(AF_INET, SOCK_DGRAM, 0);

memset(&serverAddr, '\0', sizeof(serverAddr));


serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(port);
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");

bind(sockfd, (struct sockaddr*)&serverAddr, sizeof(serverAddr));

Networking Lab Manual Dept of CSE


addr_size = sizeof(newAddr);

while(1){
int f_recv_size = recvfrom(sockfd, &frame_recv, sizeof(Frame), 0, (struct sockaddr*)&newAddr,
&addr_size);
if (f_recv_size > 0 && frame_recv.frame_kind == 1 && frame_recv.sq_no == frame_id){
printf("[+]Frame Received: %s\n", frame_recv.packet.data);

frame_send.sq_no = 0;
frame_send.frame_kind = 0;
frame_send.ack = frame_recv.sq_no + 1;
sendto(sockfd, &frame_send, sizeof(frame_send), 0, (struct sockaddr*)&newAddr,
addr_size);
printf("[+]Ack Send\n");
}else{
printf("[+]Frame Not Received\n");
}
frame_id++;
}

close(sockfd);
return 0;
}

Output
Client side

gcc client.c -o c

./c 4000
Enter Data: 1234
[+]Frame Send
[+]Ack Received
Enter Data: 0100
[+]Frame Send
[+]Ack Received
Enter Data: -5
[+]Frame Send
[+]Ack Received
Enter Data: abc
[+]Frame Send
[+]Ack Received

Server side
gcc server.c -o s
net@inlab:~/Desktop$ ./s 4000

Networking Lab Manual Dept of CSE


[+]Frame Received: 1234
[+]Ack Send
[+]Frame Received: 0100
[+]Ack Send
[+]Frame Received: -5
[+]Ack Send
[+]Frame Received: abc
[+]Ack Send

Networking Lab Manual Dept of CSE


PROGRAM 6

GO BACK N ARQ IMPLEMENTATION


Aim:- write a program to perform simulation on sliding window protocol using Go-back-N ARQ for noisy
channel.
Description:-

Go-Back-N ARQ is mainly a specific instance of Automatic Repeat Request (ARQ) protocol where the
sending process continues to send a number of frames as specified by the window size even without
receiving an acknowledgement (ACK) packet from the receiver. The sender keeps a copy of each frame
until the acknowledgement arrives.

This protocol is a practical approach to the sliding window.

● In Go-Back-N ARQ, the size of the sender window is N and the size of the receiver window is always 1.
● This protocol makes the use of cumulative acknowledgements means here the receiver maintains an
acknowledgement timer.
● If the receiver receives a corrupted frame, then it silently discards that corrupted frame and the correct
frame is retransmitted by the sender after the timeout timer expires.
● In case if the receiver receives the out of order frame then it simply discards all the frames.
● In case if the sender does not receive any acknowledgement then the frames in the entire window will
be retransmitted again.

Networking Lab Manual Dept of CSE


Networking Lab Manual Dept of CSE
SF is the sequence number of the first frame in the sliding window, SL is the sequence
number of the last frame in the sliding window. R is the sequence number of the
expected frame. W=SL-SF+1=N itself, indicating the number of frames. Only when R
and sequence number of received frame are matched, frame is accepted, otherwise
discard frame. Receiver window size is 1. Consequently, the size of the sending
window is 2^n−1. Thus in order to accommodate a sending window size of 2^n−1, an
n-bit sequence number is chosen. The maximum window size = 2^3 - 1 = 7 i.e window will
carry frames from 0 to 6 which are 7 in number. If window size is 3, we use a 2-bit sequence number to transmit
frames, i.e 2^2-1=3.

Networking Lab Manual Dept of CSE


Frame 0 &1 send, ACK 1 & 2 back to sender. Frame 2 send, ACK 3 back to sender.

Algorithm to be written in record

Networking Lab Manual Dept of CSE


Networking Lab Manual Dept of CSE
Networking Lab Manual Dept of CSE
GoBackN.c
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
int main()
{
int nf,N;
int tr=0;
srand(time(NULL));
printf("Enter the number of frames : ");
scanf("%d",&nf);
printf("Enter the Window Size : ");
scanf("%d",&N);
int i=1;
while(i<=nf)
{
int x=0;
for(int j=i;j<i+N && j<=nf;j++)
{
printf("Sent Frame %d \n", j);
tr++; //After each frame is send, increment tr by 1 to track total number of transmissions
}
for(int j=i;j<i+N && j<=nf;j++)

Networking Lab Manual Dept of CSE


{
int flag = rand()%2; //lost frame set as frame 2
if(!flag)
{
printf("%d : Acknowledged! \n", j);
x++; //After acknowledging frame, increment x indicating success of frame transmission
}
else
{ printf("Frame %d Not Received \n", j);
printf("Retransmitting Window \n");
break;
}
}
printf("\n");
i+=x; //i updates number of successful transfers - all acknowledged frames
}
printf("Total number of transmissions : %d \n", tr);
return 0; }
Output
gcc goBackN.c
net@inlab:~$ ./a.out
Enter the number of
frames : 5
Enter the Window
Size : 2
Sent Frame 1
Sent Frame 2
1 : Acknowledged!
Frame 2 Not
Received
Retransmitting
Window

Sent Frame 2
Sent Frame 3
2 : Acknowledged!
3 : Acknowledged!

Sent Frame 4
Sent Frame 5
4 : Acknowledged!
5 : Acknowledged!

Total number of
Networking Lab Manual Dept of CSE
transmissions : 6

Go-Back N Client/Server Implementation in C

gbns.c
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <fcntl.h>
#include<string.h>
#include<unistd.h>
void itoa(int number, char numberString[])

{ numberString[0] = (char)(number + 48);


//integer to ascii conversion by adding 48 and then typecasting to character
numberString[1] = '\0';
}

int main()
{
int sockfd, newSockFd, size, windowStart = 1, windowCurrent = 1, windowEnd = 4, oldWindowStart, flag;
char buffer[100];
socklen_t len;
struct sockaddr_in server, client;
server.sin_family = AF_INET;
server.sin_port = 3033;
server.sin_addr.s_addr = INADDR_ANY;
sockfd = socket(AF_INET, SOCK_STREAM, 0);

printf("\nStarting up...");
int k;
k=bind(sockfd, (struct sockaddr *)&server, sizeof(server)); //bind socket with ip addr of server
Networking Lab Manual Dept of CSE
if(k==-1)
printf("Error in binding");

len = sizeof(client);

listen(sockfd,1);
//listen to 1 active connection to client
newSockFd = accept(sockfd, (struct sockaddr *)&client,&len); //accept client connection
recv(newSockFd, buffer, 100, 0);//receive message from client

fcntl(newSockFd,F_SETFL,O_NONBLOCK);//It allows the program to place a read or a write lock.


printf("\n Received a request from client. Sending packets one by one...");
do
{
if(windowCurrent != windowEnd)
{

itoa(windowCurrent, buffer); //convert current window no to ascii and copy to buffer


send(newSockFd, buffer, 100, 0); //send window no to server through newSockFd
printf("\nPacket Sent: %d\n",windowCurrent); //show which window number the transmitted frame was
windowCurrent++; //After sending packet, increment the current window
}

recv(newSockFd, buffer, 100, 0); // receive message from Client

if(buffer[0]=='R') //check if buffer contained retransmission request packet denoting ‘R’


{
//resend packet number in buffer[1]
printf("\n** Received a RETRANSMIT packet.\n Resending packet no. %c...", buffer[1]); itoa((atoi(&buffer[1])), buffer);
//copy packet number as ascii value to buffer
send(newSockFd, buffer, 100, 0); //send packet number to client
windowCurrent = atoi(&buffer[0]); //note down the window number of retransmitted frame
windowCurrent++; //increment window after retransmission
}

else if(buffer[0] == 'A') //check if incoming buffer contained acknowledgement denoted by ‘A’
Networking Lab Manual Dept of CSE
{
oldWindowStart = windowStart; //initialize 1 as window starting index
// update the new window no based on acknowledgement from receiver
windowStart = atoi(&buffer[1]) + 1; windowEnd += (windowStart - oldWindowStart);
//print on screen which ACK was received
printf("\n** Received ACK %c. Moving window boundary.",buffer[1]);
}
}
while(windowCurrent!= 10);
close(sockfd);
close(newSockFd);
printf("\nSending Complete. Sockets closed.Exiting...\n");
return(0);
}

gbnc.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include<unistd.h>
int main()
{
int sockfd, newSockFd, size, firstTime = 1, currentPacket, wait = 3;
char data[100], digit[2];
struct sockaddr_in client;
sockfd = socket(AF_INET, SOCK_STREAM,0);

client.sin_family = AF_INET;
client.sin_port = 3033;
client.sin_addr.s_addr = INADDR_ANY;

Networking Lab Manual Dept of CSE


printf("\nStarting up...");
size = sizeof(client);
printf("\nEstablishing Connection to Server...");
connect(sockfd, (struct sockaddr *)&client, size);

sprintf(data, "REQUEST");
send(sockfd, data, strlen(data), 0); //send REQUEST message to server

do
{
recv(sockfd, data, 100, 0); //receive data from server
currentPacket = atoi(data); //note current packet number
printf("\nGot packet: %d", currentPacket);
if(currentPacket == 3 && firstTime)
{ //issue a retransmission after receiving packets until packet 3
printf("\n*** Simulation: Packet data corrupted or incomplete.");
printf("\n*** Sending RETRANSMIT for packet 1.");
memset(&data, 0, sizeof(data)); //clear buffer data
sprintf(data,"R1"); //Code for message requesting retransmission is R1 to retransmit packet 1
send(sockfd, data, strlen(data), 0);
//send R1 message to server
firstTime =0;
}
else
{ wait--; //wait time is initialized as 3ms. we can reduce wait time till 0
if(!wait)
{
printf("\n*** Packet Accepted -> Sending ACK");
wait = 3; //after accepting packet, reset wait time as 3ms
sprintf(data, "A");
digit[0] = (char)(currentPacket + 48); //convert packet number to ascii value
digit[1] = '\0';
strcat(data, digit); //concatenate A and packet number together for each packet
send(sockfd, data,strlen(data),0); //send acknowledgement to server
}
Networking Lab Manual Dept of CSE
}
}
while(currentPacket != 9);
printf("\nAll packets received...Exiting.");
close(sockfd);
return(0);
}
SERVER SIDE OUTPUT – FIRST RUN SERVER
labb04@labb04:~/Desktop$ gcc gbns1.c -o s1
labb04@labb04:~/Desktop$ ./s1

Starting up...
Recieved a request from client. Sending packets one by one...
Packet Sent: 1

Packet Sent: 2

Packet Sent: 3

** Received a RETRANSMIT packet.


Resending packet no. 1...
Packet Sent: 2

Packet Sent: 3

** Received ACK 1. Moving window boundary.


Packet Sent: 4

** Received ACK 4. Moving window boundary.


Packet Sent: 5

Packet Sent: 6

Packet Sent: 7

Networking Lab Manual Dept of CSE


** Received ACK 7. Moving window boundary.
Packet Sent: 8

Packet Sent: 9

Sending Complete. Sockets closed.Exiting…


CLIENT SIDE OUTPUT
labb04@labb04:~/Desktop$ gcc gbnc.c -o c1
labb04@labb04:~/Desktop$ ./c1

Starting up...
Establishing Connection...
Got packet: 1
Got packet: 2
Got packet: 3
*** Simulation: Packet data corrupted or incomplete.
*** Sending RETRANSMIT for packet 1.
Got packet: 1
*** Packet Accepted -> Sending ACK
Got packet: 2
Got packet: 3
Got packet: 4
*** Packet Accepted -> Sending ACK
Got packet: 5
Got packet: 6
Got packet: 7
*** Packet Accepted -> Sending ACK
Got packet: 8
Got packet: 9
All packets received...Exiting.

Networking Lab Manual Dept of CSE


PROGRAM 7
SELECTIVE REPEAT ARQ IMPLEMENTATION
Selective repeat protocol, also called Selective Repeat ARQ (Automatic Repeat request), is a data link
layer protocol that uses sliding window method for reliable delivery of data frames. Here, only the
erroneous or lost frames are retransmitted, while the good frames are received and buffered.
It uses two windows of equal size: a sending window that stores the frames to be sent and a receiving
window that stores the frames receive by the receiver. The size is half the maximum sequence number
of the frame. For example, if the sequence number is from 0 – 15, the window size will be 8.

Working Principle
Selective Repeat protocol provides for sending multiple frames depending upon the availability of frames
in the sending window, even if it does not receive acknowledgement for any frame in the interim. The
maximum number of frames that can be sent depends upon the size of the sending window.
The receiver records the sequence number of the earliest incorrect or un-received frame. It then fills the
receiving window with the subsequent frames that it has received. It sends the sequence number of the
missing frame along with every acknowledgement frame.
The sender continues to send frames that are in its sending window. Once, it has sent all the frames in
the window, it retransmits the frame whose sequence number is given by the acknowledgements. It then
continues sending the other frames.
The control variables in Selective Repeat ARQ are same as in Go-Back-N ARQ:
SF, SL and S. But the sender sliding window size changed into 2m-1.Receiver sliding window has 2
control variables, RF and RL.

Networking Lab Manual Dept of CSE


Networking Lab Manual Dept of CSE
Networking Lab Manual Dept of CSE
sr.c
The overall program counts acknowledgments and retransmissions
#include<stdio.h>

#include<stdlib.h>

int input(int a[] , int frame_size)


{
printf("\n\n Input \n\n");
for(int i = 1 ; i <= frame_size ; i++)
{
printf(" Enter Value For Frame[%d] : " , i);
scanf("%d",&a[i]);
printf("\n");
}
Networking Lab Manual Dept of CSE
printf("\n\n");
return 1;
}
int display(int a[] , int frame_size)
{
printf("\n\n Display \n\n");
for(int i = 1 ; i <= frame_size ; i++)
{
printf(" Frame[%d] : %d " , i , a[i]);
//List all frames with sequence numbers
printf("\n");
}
printf("\n\n");
return 1;
}
int selective_repeat(int frames[] , int window_size , int frame_size)
{
int nt =0;

int k = 0;

int left[10] = {-1};

int i ;

for(i = 1 ; i <= frame_size ; i++)


{
int flag = rand() % 2;
//Set frame 2 to be dropped during transmission

if(flag) //success
{
printf(" Frame[%d] with value %d Acknowledged !!! \n\n", i ,
frames[i]);
nt++; //Increment nt when frame is acknowledged
}
else
//failure
{
printf(" Frame[%d] with value %d Not Acknowledged !!! \n\n", i , frames[i]);

left[k++] = frames[i];

Networking Lab Manual Dept of CSE


//Note frame number not acknowledged and store that frame number in left 1-D
array

nt++; //count retransmission


}
if(i % window_size == 0)
{ //Loop for retransmitting lost frame
for(int x = 0 ; x < k ; x++)
{
printf(" Frame[%d] with value %d Retransmitted \n\n", x ,
left[x]);

nt++; //increment nt for retransmitted frame

printf(" Frame[%d] with value %d Acknowledged on Second


Attempt \n\n", x , left[x]);

}
k = 0;
}
}
for(i = 0 ; i < k ; i++)
{
printf(" Frame[%d] with value %d Retransmitted \n\n", i , left[i]);
//print retransmitted frame details
nt++;

printf(" Frame[%d] with value %d Acknowledged on Second Attempt \n\n",


i , left[i]);
}
printf(" Total Transmissions : %d \n\n", nt);
return 0;
}
int main()
{
int frames[50];

int window_size;

int frame_size;

printf("\n\n Selective Repeat \n\n");

Networking Lab Manual Dept of CSE


printf(" Enter Window Size : ");

scanf("%d",&window_size);

printf(" Enter Number Of Frames To Be Transmitted : ");

scanf("%d",&frame_size);

input(frames , frame_size);

display(frames , frame_size);

selective_repeat(frames , window_size , frame_size);

return 0;

net@inlab:~$ gedit sr.c


net@inlab:~$ gcc sr.c
net@inlab:~$ ./a.out

Selective Repeat

Enter Window Size : 5


Enter Number Of Frames To Be Transmitted : 10

Input

Enter Value For Frame[1] : 1

Enter Value For Frame[2] : 2

Enter Value For Frame[3] : 3

Enter Value For Frame[4] : 4

Enter Value For Frame[5] : 5

Enter Value For Frame[6] : 6

Networking Lab Manual Dept of CSE


Enter Value For Frame[7] : 7

Enter Value For Frame[8] : 8

Enter Value For Frame[9] : 9

Enter Value For Frame[10] : 10

Display

Frame[1] : 1
Frame[2] : 2
Frame[3] : 3
Frame[4] : 4
Frame[5] : 5
Frame[6] : 6
Frame[7] : 7
Frame[8] : 8
Frame[9] : 9
Frame[10] : 10

Frame[1] with value 1 Acknowledged !!!

Frame[2] with value 2 Not Acknowledged !!!

Frame[3] with value 3 Acknowledged !!!

Frame[4] with value 4 Acknowledged !!!

Frame[5] with value 5 Acknowledged !!!

Frame[0] with value 2 Retransmitted

Frame[0] with value 2 Acknowledged on Second Attempt

Frame[6] with value 6 Acknowledged !!!

Frame[7] with value 7 Not Acknowledged !!!


Networking Lab Manual Dept of CSE
Frame[8] with value 8 Not Acknowledged !!!

Frame[9] with value 9 Acknowledged !!!

Frame[10] with value 10 Acknowledged !!!

Frame[0] with value 7 Retransmitted

Frame[0] with value 7 Acknowledged on Second Attempt

Frame[1] with value 8 Retransmitted

Frame[1] with value 8 Acknowledged on Second Attempt

Total Transmissions : 13

Both Go-Back-N and Selective Repeat protocols are sliding window protocols.
Following are the important differences between Go-Back-N and Selective Repeat Protocols.
S Key Go-Back-N Selective Repeat
r.
N
o.

Definition In Go-Back-N if a sent frame is In Selective Repeat, only


found suspected or damaged then the suspected or damaged
1
all the frames are retransmitted till frames are retransmitted.
the last packet.

Sender Window Sender Window is of size N. Sender Window size is


2
Size same as N.

Receiver Receiver Window Size is 1. Receiver Window Size is


3
Window Size N.

Complexity Go-Back-N is easier to In Selective Repeat,


4 implement. receiver window needs to
sort the frames.

Efficiency Efficiency of Go-Back-N = N / (1 Efficiency of Selective


5
+ 2a). Repeat = N / (1 + 2a).

Acknowledgem Acknowledgement type is Acknowledgement type is


6
ent cumulative. individual.

Networking Lab Manual Dept of CSE


Stop and Wait protocol
Stop and Wait protocol is a protocol for flow control mechanism. In this protocol, sender sends one frame at a time
and waits for acknowledgement from the receiver. Once acknowledged, sender sends another frame to the receiver.
If acknowledgment is not received then frame/packet is retransmitted after timeout.
GoBackN protocol
GoBackN is also a protocol for flow control mechanism. In this protocol, sender sends n frames at a time and wait
for cumulative acknowledgment. If acknowledgment is not received then entire frames are retransmitted again.
Selective Repeat protocol
Selective Repeat is also a protocol for flow control mechanism. In this protocol, sender sends n frames at a time
and wait for acknowledgment of packets received in particular order. If acknowledgment is not received then lost
packets are transmitted again which is based on receiver acknowledgment. Receiver maintains a buffer of lost
packets.First, the size of the sender window is much smaller; it is 2^(m−1) . Second, the receiver
window has the same size as the sender window, i.e 2^(m-1).
Following are some of the important differences between Stop and Wait protocol and Sliding Window protocol.
S Key Stop and Wait GoBackN Selective Repeat
r protocol protocol protocol
.
N
o
.

Sender window In Stop and Wait In GoBackN In Selective Repeat


1 size protocol, Sender protocol, Sender protocol, Sender
window size is 1. window size is N. window size is N.

Receiver In Stop and Wait In GoBackN In Selective Repeat


2 Window size protocol, Receiver protocol, Receiver protocol, Receiver
window size is 1. window size is 1. window size is N.

Minimum In Stop and Wait In GoBackN In Selective Repeat


Sequence protocol, protocol, protocol, Minimum
Number Minimum Minimum Sequence Number
3 Sequence Number Sequence Number is 2N where N is
is 2. is N+1 where N is number of packets
number of packets sent.
sent.

Efficiency In Stop and Wait In GoBackN In Selective Repeat


protocol, protocol, protocol,
Efficiency Efficiency Efficiency
formular is formular is formular is
4 1/(1+2*a) where a N/(1+2*a) where a N/(1+2*a) where a
is ratio of is ratio of is ratio of
propagation delay propagation delay propagation delay
vs transmission vs transmission vs transmission
delay. delay and N is delay and N is

Networking Lab Manual Dept of CSE


S Key Stop and Wait GoBackN Selective Repeat
r protocol protocol protocol
.
N
o
.

number of packets number of packets


sent. sent.

Acknowledgem In Stop and Wait In GoBackN In Selective Repeat


ent Type protocol, protocol, protocol,
5 Acknowledgemen Acknowledgement Acknowledgement
t type is type is cumulative. type is individual.
individual.

Supported In Stop and Wait In GoBackN In Selective Repeat


Order protocol, no protocol, in-order protocol, out-of-
specific order is delivery only are order deliveries
6
needed at receiver accepted at also can be
end. receiver end. accepted at
receiver end.

Retransmission In Stop and Wait In GoBackN In Selective Repeat


s protocol, in case protocol, in case of protocol, in case of
of packet packet packet
7
drop,number of drop,numbers of drop,number of
retransmission is retransmissions are retransmission is 1.
1. N.

Networking Lab Manual Dept of CSE


CYCLE 2

PROGRAM 8
DISTANCE VECTOR ROUTING PROTOCOL
Aim

To write a C program for implementing DISTANCE Vector Routing Algorithm.

Description
This algorithm is iterative, and distributed. Each node receives information fromits directly attached
neighbours, performs some calculations and returns the result the result to its neighbouring nodes. Thisprocess
of updating the information goes on until there is no exchange of information between neighbours.

Algorithm:

(adapted from Computer Networking – A top down approach by Kurose and Rose)
Bellman Ford algoithm is applied.
Let dx(y) be the cost of the least cost path from node x to node y. Then Bellman Ford equation statesthat
dx(y) = min{ c(x,v) + dv(y) }
v
where v is a neighbour of node x. dv(y) is the cost of the least cost path from v to y. c(x,v) is the cost from x to
neighbour v. The least cost path has a value equal to minimum of c(x,v) + dv(y) over all its neighbours v. The
solution of Bellman Ford equation provides entries in node x's forwarding table.

Disstance vector (DV) algorithm


At each node x
Initialization:

for all destinations y in N:

Dx(y) = c(x,y) /* if y is not a neighbour of x, then c(x,y) = ∞ */for each neighbour w,


send distance vector Dx = { Dx(y): y in N} to w

loop:

for each y in N:
Dx(y) = min { c(x,v) + Dv(y) }
If Dx(y) changed for any destination y send distance vector Dx = {Dx(y) : y in N}to all
neighbours.
forever

Program:

Networking Lab Manual Dept of CSE


#include<stdio.h>
struct node
{
unsigned dist[20];
unsigned from[20];
}rt[10];
int main()
{
int costmat[20][20];
int n,i,j,k,count=0;
printf("Enter the nummber of nodes:");
scanf("%d",&n);
printf("Enter the cost matrix: \n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&costmat[i][j]);
costmat[i][i]=0;
rt[i].dist[j]=costmat[i][j];
rt[i].from[j]=j;
}
}
do
{
count=0;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
for(k=0;k<n;k++)
if(rt[i].dist[j]>costmat[i][k]+rt[k].dist[j])
{
rt[i].dist[j]=rt[i].dist[k]+rt[k].dist[j];
rt[i].from[j]=k;
count++;
Networking Lab Manual Dept of CSE
}
}while(count!=0);
for(i=0;i<n;i++)
{
printf("\n \n state value for router %d is \n",i+1);
for(j=0;j<n;j++)
{
printf("\t\n node %d via %d distance %d",j+1,rt[i].from[j]+1,rt[i].dist[j]);

}
}
printf("\n\n");
}

Output:

Enter the nummber of nodes:


3
Enter the cost matrix:
059
506
960

state value for router 1 is

node 1 via 1 distance 0


node 2 via 2 distance 5
node 3 via 3 distance 9

state value for router 2 is

node 1 via 1 distance 5


node 2 via 2 distance 0

Networking Lab Manual Dept of CSE


node 3 via 3 distance 6

state value for router 3 is

node 1 via 1 distance 9


node 2 via 2 distance 6
node 3 via 3 distance 0

Result

The program is executed successfully

Networking Lab Manual Dept of CSE


PROGRAM 9
LINKSTATE ROUTING PROTOCOL
(OPEN SHORTEST PATH FIRST ALGORITHM)
Aim
To write a C program for implementing Link state Routing Algorithm- OSPF.

Algorithm

Program

#include <stdio.h>
#include <string.h>
int main()
{
int count,src_router,i,j,k,w,v,min;
int cost_matrix[100][100],dist[100],last[100];
int flag[100];
printf("\n Enter the no of routers");
scanf("%d",&count);
printf("\n Enter the cost matrix values:");
for(i=0;i<count;i++)
{
for(j=0;j<count;j++)
{
printf("\n%d->%d:",i,j);
scanf("%d",&cost_matrix[i][j]);
if(cost_matrix[i][j]<0)cost_matrix[i][j]=1000;
}
}
printf("\n Enter the source router:");
scanf("%d",&src_router);
for(v=0;v<count;v++)
{
Networking Lab Manual Dept of CSE
flag[v]=0;
last[v]=src_router;
dist[v]=cost_matrix[src_router][v];
}
flag[src_router]=1;
for(i=0;i<count;i++)
{
min=1000;
for(w=0;w<count;w++)
{
if(!flag[w])
if(dist[w]<min)
{
v=w;
min=dist[w];
}
}
flag[v]=1;
for(w=0;w<count;w++)
{
if(!flag[w])
if(min+cost_matrix[v][w]<dist[w])
{
dist[w]=min+cost_matrix[v][w];
last[w]=v;
}
}
}
for(i=0;i<count;i++)
{
printf("\n%d==>%d:Path taken:%d",src_router,i,i);
w=i;
while(w!=src_router)
{
printf("\n<--%d",last[w]);w=last[w];
}
Networking Lab Manual Dept of CSE
printf("\n Shortest path cost:%d",dist[i]);
}
}

Output:

Enter the no of routers3

Enter the cost matrix values:


0->0:0

0->1:1

0->2:3

1->0:2

1->1:1

1->2:1

2->0:2

2->1:1

2->2:1

Enter the source router:1

1==>0:Path taken:0
<--1
Shortest path cost:2
1==>1:Path taken:1
Shortest path cost:1
1==>2:Path taken:2
<--1
Shortest path cost:1

Result

The program is executed successfully

Networking Lab Manual Dept of CSE


PROGRAM 10

Implementation of Simple Mail Transfer Protocol

Aim: To implement a subset of simple mail transfer protocol (SMTP) using UDP

Description:

SMTP provides for mail exchanges between users on the same or different computers. The SMTP client and
server can be divided into two components: user agent (UA) and mail transfer agent (MTA). The user agent is
a program used to send and receive mail. The actual mail transfer is done through mail transfer agents. To send
mail, a system must have client MTA, and to receive mail, a system must have a server MTA. SMTP uses
commands and responses to transfer messages between an MTA client and MTA server. Commands are sent
from the client to the server. It consists of a keyword followedby zero or more arguments. Examples: HELO,
MAIL FROM, RCPT TO etc. Responses are sent from the server to the client. It is a three-digit code that may
be followed by additional textual information. The process of transferring a mail message occurs in three
phases: connection establishmnet, mail transfer, and connection termination.

Although the transport protocol specified for SMTP is TCP, in this experiment, UDP protocol will beused.

Algorithm:

SMTP Client

1. Create the client UDP socket.

2. Send the message “SMTP REQUEST FROM CLIENT” to the server. This is done so that the
server understands the address of the client.

3. Read the first message from the server using client socket and print it.

4. The first command HELO<”Client's mail server address”> is sent by the client

5. Read the second message from the server and print it.

6. The second command MAIL FROM:<”email address of the sender”> is sent by the client.

7. Read the third message from the server and print it.

8. The third command RCPT TO:<”email address of the receiver”> is sent by the client

9. Read the fourth message from the server and print it.

Networking Lab Manual Dept of CSE


10. The fourth command DATA is sent by the client.

11. Read the fifth message from the server and print it.

12. Write the messages to the server and end with “.”

13. Read the sixth message from the server and print it.

14. The fifth command QUIT is sent by the client.

15. Read the seventh message from the server and print it.

Server

1. Create the server UDP socket

2. Read the message from the client and gets the client's address

3. Send the first command to the client.


220 “server name”

4. Read the first message from the client and print it.

5. Send the second command to the client.


250 Hello “client name”

6. Read the second message from client and print it.

7. Send the third command to the client.


250 “client email address “................................... Sender ok

8. Read the third message from client and print it

9. Send the fourth command to the client


250 “server email address” ................................. Recepient ok

10. Read the fourth message from client and print it

11. Send the fifth command to the client


354 Enter mail, end with “.” on a line by itself

12. Read the email text from the client till a “.” is reached

13. Send the sixth command to the


Networking Lab Manual Dept of CSE
client
250 Message accepted for delivery

Networking Lab Manual Dept of CSE


14. Read the fifth message from the client and print it.

15. Send the seventh command to the client


221 “server name” closing connection

Program

Client

#include<stdio.h>
#include<string.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<fcntl.h>
#include<stdlib.h>

#define MAXLINE 100 main(int


argc,char * argv[])
{

int n;

int sock_fd;int i=0;

struct sockaddr_in servaddr;char


buf[MAXLINE+1];

Networking Lab Manual Dept of CSE


char address_buf[MAXLINE],message_buf[MAXLINE];char * str_ptr,
*buf_ptr, *str;
if(argc!=3)

fprintf(stderr,"Command is :./client address port\n");exit(1);


}

if((sock_fd = socket(AF_INET, SOCK_DGRAM, 0))<0)

printf("Cannot create socket\n");exit(1);


}

bzero((char *) & servaddr,sizeof(servaddr));


servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(atoi(argv[2]));
inet_pton(AF_INET,argv[1],&servaddr.sin_addr);
sprintf(buf,"SMTP REQUEST FROM CLIENT\n");

n=sendto(sock_fd,buf,strlen(buf),0,(struct sockaddr*)&servaddr,sizeof(servaddr));if(n<0)
{

perror("ERROR");exit(1);

Networking Lab Manual Dept of CSE


}

if((n=recvfrom(sock_fd,buf,MAXLINE,0,NULL,NULL))==-1)

perror("UDP read error");exit(1);


}

buf[n]='\0';

printf("S:%s",buf);

sprintf(buf,"HELLO name_of_client_mail_server\n");

n=sendto(sock_fd,buf,strlen(buf),0,(struct sockaddr*)&servaddr,sizeof(servaddr));

if((n=recvfrom(sock_fd,buf,MAXLINE,0,NULL,NULL))==-1)

perror("UDP read error");exit(1);


}

buf[n]='\0';

printf("S:%s",buf);

printf("please enter the email address of the sender:");


fgets(address_buf,sizeof(address_buf),stdin);
address_buf[strlen(address_buf)-1]='\0';

sprintf(buf,"MAIL FROM :<%s>\n",address_buf);

Networking Lab Manual Dept of CSE


sendto(sock_fd,buf,sizeof(buf),0,(struct sockaddr*)&servaddr,sizeof(servaddr));
if((n=recvfrom(sock_fd,buf,MAXLINE,0,NULL,NULL))==-1)
{

perror("UDP read error");exit(1);


}

buf[n]='\0';

printf("S:%s",buf);

printf("please enter the email address of the receiver:");


fgets(address_buf,sizeof(address_buf),stdin);
address_buf[strlen(address_buf)-1]='\0'; sprintf(buf,"RCPT TO :
<%s>\n",address_buf);
sendto(sock_fd,buf,strlen(buf),0, (struct sockaddr *) &servaddr,sizeof(servaddr));
if((n=recvfrom(sock_fd,buf,MAXLINE,0,NULL,NULL))==-1)
{

perror("UDP read error");exit(1);


}

buf[n]='\0';

printf("S:%s",buf);
sprintf(buf,"DATA\n");
sendto(sock_fd,buf,strlen(buf),0,(struct sockaddr*)&servaddr,sizeof(servaddr));
if((n=recvfrom(sock_fd,buf,MAXLINE,0,NULL,NULL))==-1)

Networking Lab Manual Dept of CSE


{

perror("UDP read error");exit(1);


}

buf[n]='\0';

printf("S:%s",buf);

do

fgets(message_buf,sizeof(message_buf),stdin);
sprintf(buf,"%s",message_buf);
sendto(sock_fd,buf,strlen(buf),0,(struct sockaddr*)&servaddr,sizeof(servaddr));
message_buf[strlen(message_buf)-1]='\0';
str=message_buf;
while(isspace(*str++));if(strcmp(--
str,".")==0)break;
} while(1);

if((n=recvfrom(sock_fd,buf,MAXLINE,0,NULL,NULL))==-1)

perror("UDP read error");exit(1);


}

Networking Lab Manual Dept of CSE


buf[n]='\0';
sprintf(buf,"QUIT\n");
printf("S:%s",buf);
sendto(sock_fd,buf,strlen(buf),0,(struct sockaddr*)&servaddr,sizeof(servaddr));
if((n=recvfrom(sock_fd,buf,MAXLINE,0,NULL,NULL))==-1)
{

perror("UDP read error");exit(1);


}

buf[n]='\0';

printf("S:%s",buf);

Server

#include<stdio.h>
#include<string.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<fcntl.h>
#include<stdlib.h>

Networking Lab Manual Dept of CSE


#define MAXLINE 100 main(int
argc, char * argv[])
{
int n,sock_fd;

struct sockaddr_in servaddr,cliaddr;char


mesg[MAXLINE+1]; socklen_t len;
char * str_ptr, *buf_ptr, *str;
len=sizeof(cliaddr);
if((sock_fd=socket(AF_INET,SOCK_DGRAM,0))<0)

printf("cannot create socket\n");exit(1);


}

bzero((char*)&servaddr,sizeof(servaddr)); servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(atoi(argv[1]));
servaddr.sin_addr.s_addr=htonl(INADDR_ANY); if(bind(sock_fd,(struct
sockaddr*)&servaddr,sizeof(servaddr))<0)
{

perror("bind failed:");exit(1);
}

Networking Lab Manual Dept of CSE


if((n=recvfrom(sock_fd,mesg,MAXLINE,0,(struct sockaddr*)&cliaddr,&len))==-1)

perror("size not received:");exit(1);


}

mesg[n]='\0'; printf("mesg:%s\n",mesg);
sprintf(mesg,"220 name_of_server_mail_server\n");
sendto(sock_fd,mesg,MAXLINE,0,(struct sockaddr*)&cliaddr,sizeof(cliaddr));
n=recvfrom(sock_fd,mesg,MAXLINE,0,(struct sockaddr*)&cliaddr,&len); mesg[n]='\0';
printf("C:%s\n",mesg); str_ptr=strdup(mesg);
buf_ptr=strsep(&str_ptr," "); sprintf(mesg,"250
Hello %s",str_ptr);free(buf_ptr);
sendto(sock_fd, mesg, MAXLINE, 0, (struct sockaddr *)&cliaddr, sizeof(cliaddr));
n=recvfrom(sock_fd,mesg,MAXLINE,0,(struct sockaddr*)&cliaddr,&len); mesg[n]='\0';
printf("C:%s",mesg);
str_ptr=strdup(mesg);
buf_ptr=strsep(&str_ptr,":");
str_ptr[strlen(str_ptr)-1]='\0';

Networking Lab Manual Dept of CSE


sprintf(mesg,"250 Hello %s. ........................... sender ok\n",str_ptr);

free(buf_ptr);

sendto(sock_fd,mesg,MAXLINE,0,(struct sockaddr*)&cliaddr,sizeof(cliaddr));
n=recvfrom(sock_fd,mesg,MAXLINE,0,(struct sockaddr*)&cliaddr,&len); mesg[n]='\0';
printf("C:%s",mesg);
str_ptr=strdup(mesg);
buf_ptr=strsep(&str_ptr,":");
str_ptr[strlen(str_ptr)-1]='\0';
sprintf(mesg,"250 Hello %s. ........................... Recepient ok\n",str_ptr);

free(buf_ptr);

sendto(sock_fd,mesg,MAXLINE,0,(struct sockaddr*)&cliaddr,sizeof(cliaddr));
n=recvfrom(sock_fd,mesg,MAXLINE,0,(struct sockaddr*)&cliaddr,&len); mesg[n]='\0';
printf("C:%s\n",mesg);

sprintf(mesg,"354 Enter mail,end with \".\" on a line by itself \n");


sendto(sock_fd,mesg,MAXLINE,0,(struct sockaddr*)&cliaddr,sizeof(cliaddr));while(1)
{

n=recvfrom(sock_fd,mesg,MAXLINE,0,(struct sockaddr*)&cliaddr,&len); mesg[n]='\0';


printf("C:%s\n",mesg);

mesg[strlen(mesg)-1]='\0';

Networking Lab Manual Dept of CSE


str=mesg; while(isspace(*str++));
if(strcmp(--str,".")==0)break;
sprintf(mesg,"250 messages accepted for delivery \n");
sendto(sock_fd,mesg,MAXLINE,0,(struct sockaddr*)&cliaddr,sizeof(cliaddr));
n=recvfrom(sock_fd,mesg,MAXLINE,0,(struct sockaddr*)&cliaddr,&len); mesg[n]='\0';
printf("C:%s\n",mesg);

sprintf(mesg,"221 servers mail server closing connection\n");


sendto(sock_fd,mesg,MAXLINE,0,(struct sockaddr*)&cliaddr,sizeof(cliaddr));
}

Server program

#include<stdio.h>
#include<string.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<fcntl.h>
#include<stdlib.h>
#define MAXLINE 100 main(int
argc, char * argv[])
{

int n, sock_fd;
struct sockaddr_in servaddr, cliaddr;

Networking Lab Manual Dept of CSE


char mesg[MAXLINE + 1];
socklen_t len;

char * str_ptr, *buf_ptr, *str;len =


sizeof(cliaddr);

if((sock_fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)


{
printf("Cannot create socket\n");exit(1);
}

bzero((char*)&servaddr, sizeof(servaddr));

servaddr.sin_family = AF_INET; servaddr.sin_port =


htons(atoi(argv[1]));
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);

if(bind(sock_fd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0)


{
perror("bind failed:");exit(1);
}

if((n = recvfrom(sock_fd, mesg, MAXLINE, 0, (struct sockaddr *)&cliaddr, &len)) == -1)


{
perror("size not received:");exit(1);
}

mesg[n] = '\0';
printf(“mesg:%s\n”, mesg);
sprintf(mesg, “220 name_of_server_mail_server\n”);
sendto(sock_fd, mesg, MAXLINE,0, (struct sockaddr*)&cliaddr, sizeof(cliaddr));

n = recvfrom(sock_fd, mesg, MAXLINE, 0, (struct sockaddr *)&cliaddr, &len);


mesg[n] = '\0';
printf(“C:%s\n”,mesg);

str_ptr = strdup(mesg); buf_ptr =


strsep(&str_ptr, “ “);
sprintf(mesg, “250 Hello %s”, str_ptr);

Networking Lab Manual Dept of CSE


free(buf_ptr);
sendto(sock_fd, mesg, MAXLINE,0, (struct sockaddr*)&cliaddr, sizeof(cliaddr));

n = recvfrom(sock_fd, mesg, MAXLINE, 0, (struct sockaddr *)&cliaddr, &len);


mesg[n] = '\0';
printf(“C:%s\n”,mesg);

str_ptr = strdup(mesg); buf_ptr =


strsep(&str_ptr, “:“);
str_ptr[strlen(str_ptr)-1] = '\0';
sprintf(mesg, “250 Hello %s. .................. Sender ok\n”, str_ptr);
free(buf_ptr);
sendto(sock_fd, mesg, MAXLINE,0, (struct sockaddr*)&cliaddr, sizeof(cliaddr));

n = recvfrom(sock_fd, mesg, MAXLINE, 0, (struct sockaddr *)&cliaddr, &len);


mesg[n] = '\0';
printf(“C:%s\n”,mesg)

sprintf(mesg, “354 Enter mail, end with \”.\” on a line by itself\n”); sendto(sock_fd,
mesg, MAXLINE,0, (struct sockaddr*)&cliaddr, sizeof(cliaddr));

while(1)
{
n = recvfrom(sock_fd, mesg, MAXLINE, 0, (struct sockaddr *)&cliaddr, &len);mesg[n]
= '\0';
printf(“C:%s\n”,mesg);

mesg[strlen(mesg) – 1] = '\0';str =
mesg; while(isspace(*str++));
if(strcmp(--str, “.”) == 0) break;

sprintf(mesg, “250 Message accepted for delivery\n”);


sendto(sock_fd, mesg, MAXLINE,0, (struct sockaddr*)&cliaddr, sizeof(cliaddr));

n = recvfrom(sock_fd, mesg, MAXLINE, 0, (struct sockaddr *)&cliaddr, &len);mesg[n]


= '\0';
printf(“C:%s\n”,mesg);

sprintf(mesg, “221 Server's mail server closing connection\n”);


sendto(sock_fd, mesg, MAXLINE,0, (struct sockaddr*)&cliaddr, sizeof(cliaddr));

Networking Lab Manual Dept of CSE


Output

Client

Networking Lab Manual Dept of CSE


Server

Networking Lab Manual Dept of CSE


PROGRAM 11.
FILE TRANSFER PROTOCOL
Aim
To write a program to implement FTP using TCP

Algorithm

Server
1. Start.
2. Establish a tcp socket.
3. Listen over the socket.
4. Accept a connection.
5. Obtain the filename from the client.
6. Read the file.
7. Send it to the client.
8. Close the connection.
9. Stop.
This program can be compiled using 'c++ simpleftpserver.cpp' and executed './a.out'

Client
1. Start.
2. Establish a tcp connection.
3. Connect to the ftp server.
4. Send the filename.
5. Read the filecontents.
6. Create a file as required.
7. Close the connection.
8. Stop
It can be compiled using 'c++ simpleftpclient.cpp -o b' and executed './b'

Program

FTP SERVER

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<netdb.h>
int main()
{
int serversocket,clientsocket;
sockaddr_in serveraddr,clientaddr;
socklen_t len;
FILE *ptr;
char filename[20];
char file[2048],temp[500];
bzero(filename,sizeof(filename));
bzero(file,sizeof(file));

Networking Lab Manual Dept of CSE


serversocket=socket(AF_INET,SOCK_STREAM,0);
bzero((char*)&serveraddr,sizeof(serveraddr));
serveraddr.sin_family=AF_INET;
serveraddr.sin_port=htons(5015);
serveraddr.sin_addr.s_addr=INADDR_ANY
bind(serversocket,(sockaddr*)&serveraddr,sizeof(serveraddr));
bzero((char*)&clientaddr,sizeof(clientaddr));
len=sizeof(clientaddr);
listen(serversocket,5);
printf("\nWaiting for the connection\n");
clientsocket=accept(serversocket,(sockaddr*)&clientaddr,&len);
printf("\nConnection obtained.\n");
recv(clientsocket,filename,sizeof(filename),0);
printf("\nThe read filename is:\t%s\n",filename);
printf("\nReading the file.\n");
ptr=fopen(filename,"r");
while(fgets(temp,sizeof(temp),ptr)!=NULL)
{
strcat(file,temp);
}
fclose(ptr);
printf("\nSending the file.\n");
send(clientsocket,file,sizeof(file),0);
close(clientsocket);
close(serversocket);
}

FTP CLIENT

#include<iostream>
#include<stdio.h>
#include<strings.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<netdb.h>
#define FILENAME "sample.c"
int main()
{
int clientsocket;
sockaddr_in serveraddr;
hostent * server;
FILE * ptr;
char file[2048];
bzero(file,sizeof(file));
clientsocket=socket(AF_INET,SOCK_STREAM,0);
bzero((char*)&serveraddr,sizeof(serveraddr));
serveraddr.sin_family=AF_INET;
serveraddr.sin_port=htons(5015);
server=gethostbyname("127.0.0.1");
bcopy((char*)server->h_addr,(char*)&serveraddr.sin_addr.s_addr,sizeof(server->h_addr));
printf("\nTrying to connect to the server.\n");
connect(clientsocket,(sockaddr*)&serveraddr,sizeof(serveraddr));
Networking Lab Manual Dept of CSE
printf("\nConnected to the server.\n");
send(clientsocket,FILENAME,sizeof(FILENAME),0);
printf("\nSending filename.\n");
recv(clientsocket,file,sizeof(file),0);
printf("\nThe file is:\n%s",file);
ptr=fopen(FILENAME,"w");
fprintf(ptr,"%s",file);
fclose(ptr);
close(clientsocket);
}

Output

File Transfer protocol(FTP)

Client

Server

Networking Lab Manual Dept of CSE


Result
The program is executed successfully

PROGRAM 12.
CONGESTION CONTROL USING LEAKY BUCKECT ALGORITHM
Networking Lab Manual Dept of CSE
Aim
To write a program for congestion control using Leaky bucket algorithm.
Theory
The congesting control algorithms are basically divided into two groups: open loop and closed loop. Open
loop solutions attempt to solve the problem by good design, in essence, to make sure it does not
occur in the first place. Once the system is up and running, midcourse corrections are not made. Open loop
algorithms are further divided into ones that act at source versus ones that act at the destination. In contrast, closed
loop solutions are based on the concept of a feedback loop if there is any congestion. Closed loop algorithms are
also divided into two sub categories: explicit feedback and implicit feedback. In explicit feedback algorithms,
packets are sent back from the point of congestion to warn the source. In implicit algorithm, the source deduces
the existence of congestion by making local observation, such as the time needed for acknowledgment to come
back. The presence of congestion means that the load is (temporarily) greater than the resources (in part of the
system) can handle. For subnets that use virtual circuits internally, these methods can be used at the network layer.
Another open loop method to help manage congestion is forcing the packet to be transmitted at a more predictable
rate. This approach to congestion management is widely used in ATM networks and is called traffic shaping. The
other method is the leaky bucket algorithm.

Each host is connected to the network by an interface containing a leaky bucket, that is, a finite internal queue. If
a packet arrives at the queue when it is full, the packet is discarded. In other words, if one or more process are
already queued, the new packet is unceremoniously discarded. This arrangement can be built into the hardware
interface or simulate d by the host operating system. In fact it is nothing other than a single server queuing
system with constant service time.

The host is allowed to put one packet per clock tick onto the network. This mechanism turns an uneven flow of
packet from the user process inside the host into an even flow of packet onto the network, smoothing out bursts
and greatly reducing the chances of congestion.

Algorithm:
1. Start
2. Set the bucket size or the buffer size.
3. Set the output rate.
4. Transmit the packets such that there is no overflow.
Networking Lab Manual Dept of CSE
5. Repeat the process of transmission until all packets are transmitted. (Reject packets where its size is greater
than the bucket size)
6. Stop

Program
#include<stdio.h>
int main(){
int incoming, outgoing, buck_size, n, store = 0;
printf("Enter bucket size, outgoing rate and no of inputs: ");
scanf("%d %d %d", &buck_size, &outgoing, &n);

while (n != 0) {
printf("Enter the incoming packet size : ");
scanf("%d", &incoming);
printf("Incoming packet size %d\n", incoming);
if (incoming <= (buck_size - store)){
store += incoming;
printf("Bucket buffer size %d out of %d\n", store, buck_size);
} else {
printf("Dropped %d no of packets\n", incoming - (buck_size - store));
printf("Bucket buffer size %d out of %d\n", store, buck_size);
store = buck_size;
}
store = store - outgoing;
printf("After outgoing %d packets left out of %d in buffer\n", store, buck_size);
n--;
}
}
Output
Enter bucket size, outgoing rate and no of inputs: 50 100 3
Enter the incoming packet size : 50
Incoming packet size 50
Bucket buffer size 50 out of 50
After outgoing -50 packets left out of 50 in buffer
Enter the incoming packet size : 100
Incoming packet size 100
Bucket buffer size 50 out of 50
After outgoing -50 packets left out of 50 in buffer
Enter the incoming packet size : 20
Incoming packet size 20
Bucket buffer size -30 out of 50
After outgoing -130 packets left out of 50 in buffer

Networking Lab Manual Dept of CSE


PROGRAM 13

WIRESHARK TOOL
AIM:- To understand and study the wireshark tool
A Brief History of Wireshark
Wireshark has a very rich history. Gerald Combs, a computer science graduate of the University of Missouri at
Kansas City, originally developed it out of necessity. The first version of Combs’s application, called Ethereal, was
released in 1998 under the GNU Public License (GPL). Eight years after releasing Ethereal, Combs left his job to
pursue other career opportunities. Unfortunately, his employer at that time had full rights to the Ethereal
trademarks, and Combs was unable to reach an agreement that would allow him to control the Ethereal “brand.”
Instead, Combs and the rest of the development team rebranded the project as Wireshark in mid-2006 thereafter it
continued.
The Benefits of Wireshark

Supported protocols: Wireshark excels in the number of protocols that it supports more than 850 as of this writing.
These range from common ones like IP and DHCP to more advanced proprietary protocols like AppleTalk and Bit
Torrent..
User-friendliness: The Wireshark interface is one of the easiest to understand of any packet-sniffing application.
It is GUI-based, with very clearly written context menus and a straightforward
layout. It also provides several features designed to enhance usability, such as protocol-based color coding and
detailed graphical representations of raw data. Unlike some of the more complicated command-line-driven
alternatives, like tcpdump, the Wireshark GUI is great for those who are just entering the world of packet analysis.
Cost: Since it is open source, Wireshark’s pricing can’t be beat: Wire-shark is released as free software under the
GPL.
Program support: A software package’s level of support can make or break it. When dealing with freely
distributed software such as Wireshark, there may not be any formal support, which is why the open source com-
munity often relies on its user base to provide support.
Operating system support: Wireshark supports all major modern operating systems, including Windows, Mac
OS X, and Linux-based platforms.
2.3 Installing Wireshark
The Wireshark installation process is surprisingly simple. However, before you install Wireshark, make sure that
your system meets the following requirements:
More than 400 MHz processor or faster
More than 512 MB RAM
At least 75 MB of available storage space
Networking Lab Manual Dept of CSE
NIC that supports promiscuous mode

WinPcap capture driver


The WinPcap capture driver is the Windows implementation of the pcap packet-capturing application programming
interface (API). Simply put, this driver interacts with your operating system to capture raw packet data, apply
filters, and switch the NIC in and out of promiscuous mode.
First Packet Capture

1. Open Wireshark.
2. From the main drop-down menu, select Capture and then Interfaces. You should see a dialog listing the various
interfaces that can be used to capture packets, along with their IP addresses.
3. Choose the interface you wish to use, as shown in Figure-3, and click Start, or simply click the interface under
the Interface List section of the welcome page. Data should begin filling the window.
4. Wait about a minute or so, and when you are ready to stop the capture and view your data, click the Stop button
from the Capture drop-down menu.
Once you have completed these steps and finished the capture process, the Wireshark main window should be alive
with data. As a matter of fact, you might be overwhelmed by the amount of data that appears, but it will all start to
make sense very quickly as we break down the main window of Wireshark one piece at a time.
The three panes in the main window depend on one another. In order to view the details of an individual packet in
the Packet Details pane, you must first select that packet by clicking it in the Packet List pane. Once you’ve selected
your packet, you can see the bytes that correspond with a certain portion of the packet in the Packet Bytes pane
when you click that portion of the packet in the Packet Details pane.
Here’s what each pane contains:
Packet List: The top pane displays a table containing all packets in the current capture file. It has columns
containing the packet number, the relative time the packet was captured, the source and destination of the packet,
the packet’s protocol, and some general information found in the packet.
Packet Details: The middle pane contains a hierarchical display of information about a single packet. This display
can be collapsed and expanded to show all of the information collected about an individual packet.
Packet Bytes: The lower pane perhaps the most confusing displays a packet in its raw, unprocessed form; that is,
it shows what the packet looks like as it travels across the wire. This is raw information with nothing warm or
fuzzy to make it easier to follow.

Networking Lab Manual Dept of CSE


Wireshark’s preferences are divided into six major sections:
1. User Interface: These preferences determine how Wireshark presents data. You can change most options here
according to your personal preferences, including whether or not to save window positions, the layout of the three
main panes, the placement of the scroll bar, the placement of the Packet List pane columns, the fonts used to display
the captured data, and the background and foreground colors.
2. Capture These preferences allow you to specify options related to the way packets are captured, including your
default capture interface, whether to use promiscuous mode by default, and whether to update the Packet List pane
in real time.
3. Printing The preferences in this section allow you to specify various options related to the way Wireshark prints
your data.
4. Name Resolution Through these preferences, you can activate features of Wireshark that allow it to resolve
addresses into more recognizable names (including MAC, network, and transport name resolution) and specify the
maximum number of concurrent name resolution requests.
5. Statistics This section provides a few configurable options for Wireshark’s statistical features.
6. Protocols The preferences in this section allow you to manipulate options related to the capture and display of
the various packets Wireshark is capable of decoding. Not every protocol has configurable preferences, but some
have several options that can be changed.
Packet Color Coding

Each packet is displayed as a certain color for a reason. These colors reflect the packet’s protocol. For example, all
DNS traffic is blue, and all HTTP traffic is green. The color coding allows you to quickly differentiate between
various protocols so that you don’t need to read the protocol field in the Packet List pane for each individual packet.
You will find that this greatly speeds up the time it takes to browse through large capture files. Wireshark makes it
easy to see which colors are assigned to each protocol through the Coloring Rules window. To open this window,
select View from the main drop-down menu and click Coloring Rules.

Networking Lab Manual Dept of CSE


Study of working with captured packets
To save a packet capture, select File - Save As. You should see the Save File As dialog, as shown in Figure-1.
You’re asked for a location to save your packet capture and for the file format you wish to use. If you do not
specify a file format, Wireshark will use the default. pcap file format.
One of the more powerful features of the Save File As dialog is the ability to save a specific packet range. This is
a great way to thin bloated packet capture files. You can choose to save only packets in a specific number range,
marked packets, or packets visible as the result of a display filter
Merging Capture Files
Certain types of analysis require the ability to merge multiple capture files. This is a common practice when
comparing two data streams or combining streams of the same traffic that were captured separately.
To merge capture files, open one of the capture files you want to merge and choose File - Merge to bring up the
Merge with Capture File dialog, shown in Figure-2. Select the new file you wish to merge into the already open
file, and then select the method to use for merging the files. You can prepend the selected file to the currently open
one, append it, or merge the files chronologically based on their timestamps.

RESULT: Studied wireshark tool and its working.

Networking Lab Manual Dept of CSE


Networking Lab Manual Dept of CSE
Networking Lab Manual Dept of CSE
PROGRAM 11

Networking Lab Manual Dept of CSE

You might also like