Lab Mannual
Lab Mannual
CSL 332
Networking Lab
CYCLE I
CYCLE II
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.
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
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
Netstat -i
As shown above, the command with -i flag provides information on the interfaces. lo stands for
loopback interface.
3. ping
ping www.google.com
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.
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
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.
int pid;
pid = fork();
if(pid > 0)
{
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
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
8. write
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>
The AF_ prefix stands for "address family." In the first project, we are going to use AF_INET.
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>
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>
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>
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.
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>
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
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
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()
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:
Client:
Result
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));
Output
Networking Lab Manual Dept of CSE
Server
Client
Result
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
2. Generate a random number that gives the total number of frames to be transmitted.
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.
#include<stdio.h>
#include<stdlib.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;
while(noframes>0)
srand(x1++); //The srand() function sets the starting point for producing a series of pseudo-random
integers
x = rand()%10;
if(x%2 == 0)
sleep(x2);
srand(x1++);
x = rand()%10;
noframes-=1;
i++;
j++;
Output
sending frame 1
sending frame 2
Missing Acknowledgement 3
sending frame 3
sending frame 4
sending frame 5
Missing Acknowledgement 6
sending frame 6
Missing Acknowledgement 7
sending frame 7
sending frame 8
Missing Acknowledgement 9
sending frame 9
Missing Acknowledgement 10
sending frame 10
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.
GetData();
MakeFrame();
canSend=true;
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.
ReceiveFrame();
ExtractData();
int frame_id = 0;
Frame frame_send;
Frame frame_recv;
int ack_recv = 1;
while(1){
if(ack_recv == 1){
frame_send.sq_no = frame_id;
frame_send.frame_kind = 1;
frame_send.ack = 0;
if (argc != 2){
printf("Usage: %s <port>", argv[0]);
exit(0);
}
int frame_id=0;
Frame frame_recv;
Frame frame_send;
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
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.
● 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.
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
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[])
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
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;
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
Packet Sent: 3
Packet Sent: 6
Packet Sent: 7
Packet Sent: 9
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.
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.
#include<stdlib.h>
int k = 0;
int i ;
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];
}
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++;
int window_size;
int frame_size;
scanf("%d",&window_size);
scanf("%d",&frame_size);
input(frames , frame_size);
display(frames , frame_size);
return 0;
Selective Repeat
Input
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
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.
PROGRAM 8
DISTANCE VECTOR ROUTING PROTOCOL
Aim
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.
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:
}
}
printf("\n\n");
}
Output:
Result
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:
0->1:1
0->2:3
1->0:2
1->1:1
1->2:1
2->0:2
2->1:1
2->2: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
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
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.
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.
15. Read the seventh message from the server and print it.
Server
2. Read the message from the client and gets the client's address
4. Read the first message from the client and print it.
12. Read the email text from the client till a “.” is reached
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>
int n;
n=sendto(sock_fd,buf,strlen(buf),0,(struct sockaddr*)&servaddr,sizeof(servaddr));if(n<0)
{
perror("ERROR");exit(1);
if((n=recvfrom(sock_fd,buf,MAXLINE,0,NULL,NULL))==-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)
buf[n]='\0';
printf("S:%s",buf);
buf[n]='\0';
printf("S:%s",buf);
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)
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)
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>
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);
}
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';
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);
mesg[strlen(mesg)-1]='\0';
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;
bzero((char*)&servaddr, sizeof(servaddr));
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));
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;
Client
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));
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
Client
Server
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
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
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.
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.