CN Lab Final Record
CN Lab Final Record
EXPERIMENT-1
Aim:
Implement the data link layer framing methods such as character count,
character stuffing and bit stuffing.
Description:
The Data Link Layer is the second layer in the OSI model, above the Physical Layer, which ensures
that the error free data is transferred between the adjacent nodes in the network. It
breaks the data grams passed down by above layers and convert them into frames ready for
transfer. This is called Framing. It provides two main functionalities
Reliable data transfer service between two peer network layers
Flow Control mechanism which regulates the flow of frames such that data congestion
is not there at slow receivers due to fast senders.
What is Framing?
Since the physical layer merely accepts and transmits a stream of bits without any regard to
meaning or structure, it is up to the data link layer to create and recognize frame boundaries.
This can be accomplished by attaching special bit patterns to the beginning and end of the
frame. If these bit patterns can accidentally occur in data, special care must be taken to make
sure these patterns are not incorrectly interpreted as frame delimiters. The four framing
methods that are widely used are
Character count
Starting and ending characters, with character stuffing
Starting and ending flags, with bit stuffing
Physical layer coding violations
Character stuffing
In the second method, each frame starts with the ASCII character sequence DLE STX and
ends with the sequence DLE ETX.(where DLE is Data Link Escape, STX is Start of TeXt and
ETX is End of TeXt.) This method overcomes the drawbacks of the character count method. If
the destination ever loses synchronization, it only has to look for DLE STX and DLE ETX
characters. If however, binary data is being transmitted then there exists a possibility of the
characters DLE STX and DLE ETX occurring in the data. Since this can interfere with the
framing, a technique called character stuffing is used. The sender's data link layer inserts an
1
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
ASCII DLE character just before the DLE character in the data. The receiver's data link layer
removes this DLE before this data is given to the network layer. However character stuffing is
closely associated with 8-bit characters and this is a major hurdle in transmitting arbitrary sized
characters.
2
DHANEKULA INSTITUTE OF ENGG & TECH CN&NPLAB
if(str[i]=='D') {
if(str[i+1]=='L') {
if (str [i+2]=='E') {
printf (" DLE DLE ");
i+=2;
continue;
}
}
}
printf(" %c DLE ",str[i]);
} // end of loop
if(i<strlen(str))
printf("%c ",str[strlen(str)-1]);
printf(" DLE ETX ");
printf("\nAfter bits unstuffing \n");
printf("\nAt Receiver side ");
for(i=0;i<strlen(str);i++)
printf("%c ",str[i]);
}
Output:
Enter input String: abcDLEc
After byte stuffing
Sender Side
DLETX DLE a DLE b DLE DLE DLE c DLEETX
After bits unstuffing
At Receiver Side abDLEc.
3
DHANEKULA INSTITUTE OF ENGG & TECH CN&NPLAB
Bit stuffing:-
The third method allows data frames to contain an arbitrary number of bits and allows
character codes with an arbitrary number of bits per character. At the start and end of each
frame is a flag byte consisting of the special bit pattern 01111110. Whenever the sender's data
link layer encounters five consecutive 1s in the data, it automatically stuffs a zero bit into the
outgoing bit stream. This technique is called bit stuffing. When the receiver sees five
consecutive 1s in the incoming data stream, followed by a zero bit, it automatically destuffs the 0 bit. The
boundary between two frames can be determined by locating the flag pattern.
4
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
#include <stdio.h>
void main() {
if(flag==5) {
printf(" 0 ");
flag=0;
}
if(str[i]=='1') {
flag++;
}
else
flag=0;
printf(" %c ",str[i]);
}
printf("\nAfter bits unstuffing \n");
printf("\nAt Receiver side ");
for(i=0;i<strlen(str);i++)
printf("%c ",str[i]);
}
Output:
Enter input String: 001111110
After bits stuffing
Sender Side 0011111010
After bits unstuffing
At Receiver Side 001111110.
5
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
EXPERIMENT-2
Aim:
Implement the error correcting code Cyclic Redundancy Check (CRC) of
data link layer using various polynomials like CRC-CRC 12,
CRC 16 and CRC CCIPP.
Description:
The Data Link Layer is the second layer in the OSI model, above the Physical
Layer, which ensures that the error free data is transferred between the adjacent nodes in the
network. It breaks the datagram passed down by above layers and converts them into frames
ready for transfer. This is called Framing. It provides two main functionalities
Reliable data transfer service between two peer network layers
Flow Control mechanism, which regulates the flow of frames such that data
congestion is not there at slow receivers due to fast senders.
There are two basic strategies for dealing with errors. One way is to include
enough redundant information (extra bits are introduced into the data stream at the
transmitter on a regular and logical basis) along with each block of data sent to enable
the receiver to deduce what the transmitted character must have been. The other way is
to include only enough redundancy to allow the receiver to deduce that error has
occurred, but not which error has occurred and the receiver asks for a retransmission.
The former strategy uses Error-Correcting Codes and latter uses Error-detecting Codes.
This Cyclic Redundancy Check is the most powerful and easy to implement
technique. Unlike checksum scheme, which is based on addition, CRC is based on
binary division. In CRC, a sequence of redundant bits, called cyclic redundancy check
bits, are appended to the end of data unit so that the resulting data unit becomes
exactly divisible by a second, predetermined binary number. At the destination, the
incoming data unit is divided by the same number. If at this step there is no remainder, the data
unit is assumed to be correct and is therefore accepted. A remainder indicates that the data unit
has been damaged in transit and therefore must be rejected.
6
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
1. Bit strings are created as representation of polynomials with coefficients '0' and
'1'only.
2. A k-bit frame is regarded as coefficients list for a polynomial with 'k' terms (xk-1 to
x0 )
When this method is used, the sender and the receiver should agree upon a
Both the high and low order bits of G(x) must be '1'
To compute checksum for some frame with 'm' bits ( polynomial = M(x), append 'r'
zero bits to the lower end of the frame (r = degree of the generator polynomial)
Divide M(x) by G(x) using modulo-2 division and subtract the remainder from M(x)
1. Let 'r' be the degree of G(x). Append 'r' to the lower end of the frame so that it
contains (m + r) bits.
7
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
G(x) = x4 +x +1 = 10011
è degree = 4
èM(x) = 11010110110000
8
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
9
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
Performance:
CRC is a very effective error detection technique. If the divisor is chosen according
to the previously mentioned rules, its performance can be summarized as follows:
Program:
10
DHANEKULA INSTITUTE OF ENGG & TECH CN&NPLAB
int main()
{
int flag=0;
do{
printf("\n1.crc12\n2.crc16\ncrc ccit\n4.exit\n\nEnter your option.");
scanf("%d",&b);
switch(b)
{
case 1:strcpy(g,"1100000001111");
break;
case 2:strcpy(g,"11000000000000101");
break;
case 3:strcpy(g,"10001000000100001");
break;
case 4:return 0;
}
printf("\n enter data:");
scanf("%s",t);
printf("\n-----------------------\n");
printf("\n generating polynomial:%s",g);
a=strlen(t);
for(e=a;e<a+N-1;e++)
t[e]='0';
printf("\n--------------------------\n");
printf("mod-ified data is:%s",t);
printf("\n-----------------------\n");
crc();
printf("checksum is:%s",cs);
for(e=a;e<a+N-1;e++)
t[e]=cs[e-a];
printf("\n-----------------------\n"); printf("\n
final codeword is : %s",t); printf("\n---------
---------------\n");
printf("\ntest error detection 0(yes) 1(no)?:");
scanf("%d",&e);
if(e==0)
{
do{
printf("\n\tenter the position where error is to be inserted:");
scanf("%d",&e);
}
while(e==0||e>a+N-1);
t[e-1]=(t[e-1]=='0')?'1':'0';
11
DHANEKULA INSTITUTE OF ENGG & TECH CN&NPLAB
printf("\n-----------------------\n");
printf("\n\terroneous data:%s\n",t);
}
crc();
for(e=0;(e<N-1)&&(cs[e]!='1');e++);
if(e<N-1)
printf("error detected\n\n");
else
printf("\n no error detected \n\n");
printf("\n-----------------------");
}while(flag!=1);
}
Output:
1.crc12 2.crc16
3.crc ccit
4.exit
enter data:1100110011100011
-----------------------
generating polynomial:1100000001111
-------------------------
mod-ified data is:11001100111000110000000000001100000001111
-----------------------
checksum is:1101110110001
-----------------------
final codeword is : 11001100111000111101110110001100000001111
------------------------
test error detection 0(yes) 1(no)?:1
no error detected
-----------------------
1.crc12 2.crc16
3.crc ccit
4.exit
Enter your option.2
enter data:11001100111000
-----------------------
12
DHANEKULA INSTITUTE OF ENGG & TECH CN&NPLAB
generating polynomial:11000000000000101
--------------------------
mod-ified data
is:110011001110000000000000000000000000000000101
-----------------------
checksum is:11111111110110000
-----------------------
final codeword is : 110011001110001111111111011000000000000000101
------------------------
test error detection 0(yes) 1(no)?:1
no error detected
-----------------------
1.crc12 2.crc16
3.crc ccit
4.exit
Enter your option.3
enter data:11001100111000
-----------------------
generating polynomial:10001000000100001
--------------------------
mod-ified data is:110011001110000000000000000000001000000100001
-----------------------
checksum is:11100111100111010
-----------------------
final codeword is : 110011001110001110011110011101001000000100001
------------------------
test error detection 0(yes) 1(no)?:0
-----------------------
1.crc12 2.crc16
3.crc ccit
4.exit
Enter your option.4
Result:
Thus the program for cyclic redundancy check is executed.
13
DHANEKULA INSTITUTE OF ENGG & TECH CN&NPLAB
EXPERIMENT-3
Aim:
Implement Dijkstra 's algorithm to compute the Shortest path through a graph.
Description:
It is a static routing algorithm. It is used to build a graph of the subnet, with each node of
graph representing a router and each arc of the graph representing a communication
line. To choose a route between a given pair of routers, the algorithm just finds the
shortest path between them on the graph. Different ways of measuring the path length
is the number of Hops, Geographical distance in kmts, Mean Queuing delay,
Transmission delay, Functions of distance, Bandwidth, Average traffic, communication
cost etc.,
Several algorithms for computing the shortest path between two nodes of a graph are
known. This one is due to Dijkstra (1959). Each node is labeled (in parentheses) with its distance
from the source node along the best known path. Initially, no paths are known,
so all nodes are labeled with infinity. As the algorithm proceeds and paths are found,
the labels may change, reflecting better paths. A label may be either tentative or
permanent. Initially, all labels are tentative. When it is discovered that a label represents the
shortest possible path from the source to that node, it is made permanent and never changed
thereafter.
To illustrate how the labeling algorithm works, look at the weighted, undirected graph of
Fig. (a), where the weights represent, for example, distance. We want to find the
shortest path from A to D. We start out by marking node A as permanent, indicated by a
filled-in circle. Then we examine, in turn, each of the nodes adjacent to A (the working
node), relabeling each one with the distance to A. Whenever a node is relabeled, we also label
it with the node from which the probe was made so that we can reconstruct the final path later.
Having examined each of the nodes adjacent to A, we examine all
the tentatively labeled nodes in the whole graph and make the one with the smallest label
permanent, as shown in Fig. (b). This one becomes the new working node.
14
DHANEKULA INSTITUTE OF ENGG & TECH CN&NPLAB
We now start at B and examine all nodes adjacent to it. If the sum of the label on B and
the distance from B to the node being considered is less than the label on that node, we have a
shorter path, so the node is relabeled.
After all the nodes adjacent to the working node have been inspected and the tentative labels
changed if possible, the entire graph is searched for the tentatively-labeled node with the smallest
value. This node is made permanent and becomes the working node for the next round. Figure
shows the first five steps of the algorithm.
To see why the algorithm works, look at Fig. (c). At that point we have just made E
permanent. Suppose that there were a shorter path than ABE, say AXYZE. There are
two possibilities: either node Z has already been made permanent, or it has not been. If
it has, then E has already been probed (on the round following the one when Z was
made permanent), so the AXYZE path has not escaped our attention and thus cannot be a shorter
path.
Now consider the case where Z is still tentatively labeled. Either the label at Z is greater than or
equal to that at E, in which case AXYZE cannot be a shorter path than ABE, or it is less than that
of E, in which case Z and not E will become permanent first, allowing E to be probed from Z.
This algorithm is given in Fig. 5-8. The global variables n and dist describe the graph
and are initialized before shortest_path is called. The only difference between the
program and the algorithm described above is that in Fig. 5-8, we compute the shortest
path starting at the terminal node, t, rather than at the source node, s. Since the
shortest path from t to s in an undirected graph is the same as the shortest path from s to t, it does
not matter at which end we begin (unless there are several shortest paths,
in which case reversing the search might discover a different one). The reason for
searching backward is that each node is labeled with its predecessor rather than its
successor. When the final path is copied into the output variable, path, the path is thus reversed.
By reversing the search, the two effects cancel, and the answer is produced in the correct order.
15
DHANEKULAINSTITUTE OF ENGG & TECH CN&NPLAB
Figure: The first five steps used in computing the shortest path from A to D. The arrows
D(10,H) = H(8,F)
= F(6,E)
= E(4,B)
= B(2,A)
= A
Program:
#include<stdio.h>
#include<stdlib.h>
#define MAX_NODES 1024
#define INFINITY 1000
16
DHANEKULA INSTITUTE OF ENGG & TECH CN&NPLAB
int n=8,cost=0,dist[8][8]={{0,2,0,0,0,0,6,0},
{2,0,7,0,2,0,0,0},
{0,7,0,3,0,3,0,0},
{0,0,3,0,0,0,0,2},
{0,2,0,0,0,2,1,0},
{0,0,3,0,2,0,0,2},
{6,0,0,0,1,0,0,4},
{0,0,0,2,0,2,4,0}};
for(p=&state[0];p<&state[n];p++)
{
p->pre=-1;
p->length=INFINITY;
p->label=0;
}
state[0].length=0;
state[0].label=1;
state[0].pre=-1;
k=t;
do
{
for(i=0;i<n;i++)
if(dist[k][i]!=0 && state[i].label==0)
{
if(state[k].length+dist[k][i]<state[i].length)
{
state[i].pre=k;
state[i].length=state[k].length+dist[k][i];
}
17
DHANEKULA INSTITUTE OF ENGG & TECH CN&NPLAB
k=0;
min=INFINITY;
for(i=0;i<n;i++)
}while(k!=s);
i=0;
k=s;
do
{
path[i++]=k;
k=state[k].pre;
cost+=state[k].length;
}while(k>=0);
return i;
}
void main()
{
int i,j,m,path[102],q,p;
m=shortest_dist(q-1,p-1,path);
for(i=0;i<m;i++)
{
printf(" %c-> ",path[i]+'A');
18
DHANEKULA INSTITUTE OF ENGG & TECH CN&NPLAB
Output:
Enter Number of nodes(1-8): 7
Result:
Thus the program Implement Dijkstra 's algorithm to compute the Shortest path
through a graph is executed
19
DHANEKULA INSTITUTE OF ENGG & TECH CN&NPLAB
EXPERIMENT-4
Aim:
Take an example subnet graph with weights indicating delay between
nodes. Now obtain Routing table art each node using distance vector
routing algorithm
Description:
The starting assumption for distance-vector routing is that each node knows the cost of
the link to each of its directly connected neighbors. A link
that is down is assigned an infinite cost.
Example.
0 1 1 � 1 1 �
A
1 0 1 � � � �
B
20
DHANEKULA INSTITUTE OF ENGG & TECH CN&NPLAB
1 1 0 1 � � �
C
� � 1 0 � � 1
D
1 � � � 0 � �
E
1 � � � � 0 1
F
� � � 1 � 1 0
G
1. Every node sends a message to its directly connected neighbors containing its
personal list of distance. ( for example, A sends its information to its
neighbors B,C,E, and F. )
2. If any of the recipients of the information from A find that A is advertising a path
shorter than the one they currently know about, they update their list to give the
new path length and note that they should send packets for that destination
through A. ( node B learns from A that node E can be reached at a cost of
1; B also knows it can reach A at a cost of 1, so it adds these to get the cost of reaching
E by means of A. B records that it can reach E at a cost of 2 by going
through A.)
3. After every node has exchanged a few updates with its directly connected
neighbors, all nodes will know the least-cost path to all the other nodes.
4. In addition to updating their list of distances when they receive updates, the
nodes need to keep track of which node told them about the path that they used
21
DHANEKULA INSTITUTE OF ENGG & TECH CN&NPLAB
to calculate the cost, so that they can create their forwarding table. ( for
example, B knows that it was A who said " I can reach E in one hop" and
so B puts an entry in its table that says " To reach E, use the link to A.)
0 1 1 2 1 1 2
A
1 0 1 2 2 2 3
B
1 1 0 1 2 2 2
C
2 1 0 3 2 1
D
1 2 2 3 0 2 3
E
1 2 2 2 2 0 1
F
3 2 1 3 1 0
G
For example, Table 3 shows the complete routing table maintained at node B for the
network in figure1.
22
DHANEKULA INSTITUTE OF ENGG & TECH CN&NPLAB
1 A
A
1 C
C
2 C
D
2 A
E
2 A
F
3 A
G
Program:
#include<stdio.h>
struct node
{
unsigned dist[20];
unsigned from[20];
}rt[10];
int main()
{
int dmat[20][20];
int n,i,j,k,count=0;
printf("enter the number of nodes:");
scanf("%d",&n);
printf("enter the cost matrix :\n");
for(i=0;i<n;i++)
23
DHANEKULA INSTITUTE OFENGG & TECH CN&NPLAB
for(j=0;j<n;j++)
{
scanf("%d",&dmat[i][j]);
dmat[i][i]=0;
rt[i].dist[j]=dmat[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]>dmat[i][k]+rt[k].dist[j])
{
rt[i].dist[j]=rt[i].dist[k]+rt[k].dist[j];
rt[i].from[j]=k;
count++;
}
}while(count!=0);
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
printf("\n state value for router %d is\n",i+1);
for(j=0;j<n;j++)
{
printf("\n node %d via %d Distance %d", j+1,rt[i].from[j]+1,rt[i].dist[j]);
}}
printf("\n");
}
Output:
24
DHANEKULA INSTITUTE OF ENGG &TECH CN&NPLAB
Result:
Thus the program for obtain Routing table art each node using distance vector routing
algorithm is executed.
25
DHANEKULA INSTITUTE OF ENGG &TECH CN&NPLAB
EXPERIMENT-5
Aim:
Take an example subnet of hosts. Obtain broadcast tree for it.
Description:
Sending a packet to all destinations simultaneously is called broadcasting. The set of
optimal routes from a source to all destinations form a tree rooted at the source. Such a tree is
called a sink tree. It is illustrated in Fig., where the distance metric is the number of hops. Note
that a sink tree is not necessarily unique; other trees with the same path
lengths may exist. The goal of all routing algorithms is to discover and use the sink trees
for all routers
Program:
#include<stdio.h>
#include<stdlib.h>
#define MAX_NODES 20
#define INFINITY 1000
26
DHANEKULA INSTITUTE OF ENGG & TECH CN&NPLAB
int path[MAX_NODES][MAX_NODES];
int main()
{
int num_nodes=0;
int i=0,j=0;
int path_len,hops[MAX_NODES];
27
DHANEKULA INSTITUTE OF ENGG & TECH CN&NPLAB
int prev;
int length;
enum {perm,tent} label;
}state[MAX_NODES];
int i,j,k,min; int
count=0;
struct state *p;
for(p=&state[0];p<&state[n];p++)
{
p->prev= -1;
p->length= INFINITY;
p->label= tent;
}
state[s].length= 0;state[s].label= perm;
k=s;
do
{
for(i=0;i<n;i++)
if(dist[k][i]!=0&&state[i].label==tent)
{
if(state[k].length+dist[k][i]<state[i].length)
{
state[i].prev=k;
state[i].length=state[k].length+dist[k][i];
}
}
k=0;
min=INFINITY;
for(i=0;i<n;i++)
if(state[i].label==tent&&state[i].length<min)
{
min=state[i].length;
k=i;
}
state[k].label=perm;
count++;
}while(count<n);
for(j=0;j<n;j++)
{
i=0;k=j;
do
{
path[j][i++]=k;
k=state[k].prev;
28
DHANEKULA INSTITUTE OF ENGG & TECH CN&NPLAB
While (k>=0);
hops[j]=i;
}
}
Output:
->0->2 ->1->2
->2
->3->2
Result:
Thus the program to obtain broadcast tree for an example subnet of hosts is executed.
29
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
WEEK1:
AIM: Implement the following forms of IPC
a) Pipes b)FIFO
a) Pipes:
DESCRIPTION:
There is no form of IPC that is simpler than pipes, Implemented on every flavor of UNIX.
Basically, a call to the pipe() function returns a pair of file descriptors. One of these descriptors
is connected to the write end of the pipe, and the other is connected to the read
end. Anything can be written to the pipe, and read from the other end in the order it came in. On
many systems, pipes will fill up after you write about 10K to them without reading anything out.
The following example shows how a pipe is created, reading and writing from pipe.
A pipe is created by the pipe system call. int pipe ( int *filedes ) ;
Two file descriptors are returned- filedes[0] which is open for reading , and filedes[1] which is open
for writing.
6 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
Pipes are typically used to communicate between two different processes in the following
way. First, a process creates a pipe and then forks to create a copy of itself, as shown
above figure.
Next the parent process closes the read end of the pipe and the child process closes the write end of
the pipe.
The fork system call creates a copy of the process that was executing.
The process that executed the fork is called the parent process and the new process is called the child
process.
1) The first return value in the parent process is the process ID of the newly created
child process.
2) The second return value in the child process is zero.
If the fork system call is not successful, -1 is returned
Pseudo code:
START
Store any message in one character array ( char *msg="Hello world")
Declare another character array
Create a pipe by using pipe() system call
Create another process by executing fork() system call
In parent process use system call write() to write message from one process to
another process.
In child process display the message.
END
/* CREATION OF A ONEWAY PIPE IN A SINGLE PROCESS. */
PROGRAM
#include<stdio.h>#include<
stdlib.h>
main()
{
int pipefd[2],n;
char buff[100];
pipe(pipefd);
printf("\nreadfd=%d",pipefd[0]);
printf("\nwritefd=%d",pipefd[1]);
7 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
write(pipefd[1],"helloworld",12);
n=read(pipefd[1],buff,sizeof(buff));
printf("\n size of the data%d",n);
printf("\n data from pipe:%s",buff);
}
OUTPUT:
readfd=3
writefd=4
size of the data : 12
data from pipe: helloworld
PROGRAM
#include<stdio.h>
#include<stdlib.h>
main()
{
int pipefd[2],n,pid;
char buff[100];
pipe(pipefd);
printf("\n readfd=%d",pipefd[0]);
printf("\n writefd=%d",pipefd[1]);
pid=fork();
if(pid==0)
{
close(pipefd[0]);
printf("\n CHILD PROCESS SENDINGDATA\n");
write(pipefd[1],"hello world",12);
}
else
{
close(pipefd[1]);
printf("PARENT PROCESS RECEIVESDATA\n");
n=read(pipefd[0],buff,sizeof(buff));
printf("\n size of data%d",n);
printf("\n data received from child throughpipe:%s\n",buff);
}
}
8 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
OUTPUT
Readfd=3
Writefd=4
PARENTPROCESSRECIEVESDATA
Writefd =4
CHILDPROCESSSENDINGDATA
Size of data 12
PROGRAM
#include<stdio.h>
#include<stdlib.h>
main()
{
int p1[2],p2[2],n,pid;
char buf1[25],buf2[25];
pipe(p1);
pipe(p2);
printf("\n readfds=%d %d\n",p1[0],p2[0]);
printf("\n writefds=%d%d\n",p1[1],p2[1]);
pid=fork();
if(pid==0)
{
close(p1[0]);
printf("\n CHILD PROCESS SENDING
DATA\n"); write(p1[1],"where is DIET",25);
close(p2[1]);
read(p2[0],buf1,25);
printf(" reply from
parent:%s\n",buf1); sleep(2);
}
else
{
close(p1[1]);
printf("\n parent process receiving data\n");
n=read(p1[0],buf2,sizeof(buf2));
printf("\n data received from child through
pipe:%s\n",buf2); sleep(3);
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
close(p2[0]);
write(p2[1]," in ganguru",20);
printf("\n reply send\n");
}
}
OUTPUT:
readfds=3 5
writefds=4 6
CHILDPROCESSSENDINGDATA
parent process receiving data
data received from child through pipe:where is DIET
reply send
reply from parent: in ganguru
9 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
b) FIFO:
DESCRIPTION:
A FIFO ("First In, First Out") is sometimes known as a named pipe. That is, it's like a pipe, except that it
has a name! In this case, the name is that of a file that multiple processes can
open() and read and write to.
This latter aspect of FIFOs is designed to let them get around one of the shortcomings of normal
pipes: you can't get one end of a normal pipe that was created by an unrelated
process. See, if I run two individual copies of a program, they can both call pipe() all they
want and still not be able to communicate to one another. (This is because you must pipe(), then fork()
to get a child process that can communicate to the parent via the pipe.) With FIFOs, though, each
unrelated process can simply open() the pipe and transfer data through
it.
Since the FIFO is actually a file on disk, we have to call mknod() with the proper arguments
create it.. Here is a mknod() call that creates a FIFO:
Pathname = is the name of the fifo file . Mode = The mode argument specifies the file mode access
mode and is logically or' ed with the S_IFIFO flag.
In the above example, the FIFO file will be called "myfifo". The second argument is the
creation mode, which is used to tell mknod() to make a FIFO (the S_IFIFO part of the OR)
and sets access permissions to that file (octal 644, or rw-r--r--) which can also be set by
ORing together macros from sys/stat.h. Finally, a device number is passed. This is ignored
10 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
when creating a FIFO, so you can put anything you want in there. Once the FIFO has been
created, a process can start up and open it for reading or writing using the standard open()
system call.
Note: a FIFO can also be created from the command line using the Unixmknod command.
Here is a small example of FIFO. This is a simulation of Producers and Consumers Problem.
Two programs are presented Producer.c and Consumer.c where Producer writes into FIFO
and Consumer reads from FIFO.
START
END
START
END
11 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
PROGRAM
SERVERProgram
#include<stdio.h>#include<
ctype.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdlib.h>
#include<string.h>
main()
{
int wrfd,rdfd,n,d,ret_val,count;
char buf[50];
/*create the first named pipe */
ret_val=mkfifo("np1",0666);
/*create the second named pipe */
ret_val=mkfifo("np2",0666);
/*open the first named pipe for
reading*/ rdfd=open("np1",O_RDONLY);
/*open the second named pipe for writing*/
wrfd=open("np2",O_WRONLY);
write(wrfd,buf,strlen(buf));
}
FIFO SERVEROUTPUT:
12 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
CLIENT PROGRAM
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
main()
{
int wrfd,rdfd,n;
char buf[50],line[50];
/*open the first named pipe for writing*/
wrfd=open("np1",O_WRONLY);
/*create the second named pipe for reading
*/ rdfd=open("np2",O_RDONLY);
/*write to the pipe*/
printf("enter line of text");
gets(line);
write(wrfd,line,strlen(line));
/*read from the pipe*/
n=read(rdfd,buf,50);
buf[n]='\0';//end of line
printf("full duplex client:read from the pipe:%s\n",buf);
13 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
WEEK-2
DESCRIPTION:
Ftok() Semget()
#include <sys/types.h>
#include<sys/ipc.h>
The file <sys/types.h> defines the key_t datatype, which is typically a 32-bit integer.
¸ System V IPC keys are used to identify message queues, shared memory, and semaphores.
¸ If the pathname does not exist, or is not accessible to the calling process, ftok returns -1.
¸ Once the pathname and proj are agreed on by the client and server, then both can call the ftok function to
convert these into the same IPC key.
The value returned by msgget is the message queue identifier, msqid, or -1 if an error occurred.
msgsnd system call:
once a message queue is opended with msgget,we put a message otn the queue
using the msgsnd system call.
14 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
int msgrcv(int msqid,struct msgbuf *ptr, int length, long msgtype, int flag);
the msgctl system call providea a variety of control operations on a message queue .
15 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
Pseudo code:
START
Initialize character array with string.
Message queues are implemented as linked lists of data stored in shared memory. The
message queue itself contains a series of data structures, one for each message, each
of which identifies the address, type, and size of the message plus a pointer to the next
message in the queue.
To allocate a queue, a program uses the msgget() system call. Messages are placed in
the queue by msgsnd() system calls and retrieved by msgrcv() . Other operations related
to managing a given message queue are performed by the msgctl() system call.
PROGRAM
SERVERProgram
16 Dept CEoS
#include<sys/types.h>
#include<sys/ipc.h>
#include<stdlib.h>
#include<stdio.h>
#include<unistd.h>
#include<string.h>
main()
{
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
int msqid,l;
msqid=msgget(val,IPC_CREAT|0666);
msgrcv(msqid,buf,sizeof(buf),0,0);
exit(0);
}
MESSAGE serverOUTPUT:
Received file name: test.txt
CLIENT PROGRAM
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<stdio.h>
#include<unistd.h>
#include<string.h>
main()
buf[50]; key_t
val=1234;
msqid=msgget(val,IPC_CREAT|0666);
scanf("%s",buf);
msgsnd(msqid,buf,sizeof(buf),0);
MESSAGE 17
clientOUTPUT: Enter file name: test.txt Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
WEEK-4 &5
AIM: Design TCP iterative Client and server application to reverse the given input sentence.
DECRIPTION:
Socket function:
#include <sys/socket.h>
int socket int family, int type, int protocol);
Family Description
Type Description
The protocol argument to the socket function is set to zero except for raw sockets.
Connect function: The connect function is used by a TCP client to establish a connection with a TCP
server.
int connect(int sockfd, const struct sockaddr *servaddr, socklen_t addrlen);
Bind function: The bind function assigns a local protocol address to a socket.
int bind(int sockfd, const struct sockaddr *myaddr, s ocklen_t addrlen);
Bzero: It sets the specified number of bytes to 0(zero) in the destination. We often use this function to
initialize a socket address structure to 0(zero).
#include<strings.h>
void bzer(void *dest,size_t nbytes);
Memset: It sets the specified number of bytes to the value c in the destination.
#include<string.h>
void *memset(void *dest, int c, size_t len);
23 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
Close function: The normal UNIX close function is also used to close a socket and terminate a TCP
connection.
#include<unistd.h>
int close(int sockfd);
Return 0 if ok, -1 on error.
Listen function: The second argument to this function specifies the maximum number of connection
that the kernel should queue for this socket.
int listen(int sockfd, int backlog);
Accept function: The cliaddr and addrlen argument are used to ret urn the protocol address of the
connected peer processes (client)
struct in_addr
{
in_addr_t s_addr; /* network byte ordered */
};
struct sockaddr_in
{
uint8_t sin_len; /* length of structure(16) */
sa_family_t sin_family; /* AF_INET */
in_port_t sin_port; /* 16-bit TCP or UDP port number*/
/* network byte ordered */
struct in_addr sin_addr; /* 32-bit IPv4 address */
/*newtork byte ordered */
char sin_zero[8]; /* unused */
};
Address Conversion functions
#include<netinet/in.h>
Uint16_t htons( uint16_t host16bitvalue);
Uint32_t htonl( uint32_t host32bitvalue); Uint16_t
ntohs( uint16_t net16bitvalue); Uint32_t
ntohl( uint32_t net32bitvalue);
24 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
25 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
Pseudo code:
START
Client sends message to server using sent functions.
Server receives all the messages, server ignores all the consonants in the message. All the vowels
in the message are converted into upper case.
Server returns the entire message to clients (with toggled vowel cases).
END
For example: "This is a test and sample message." to server will be sent back to client as
"ThIs Is A tEst And sAmplE mEssAgE."
When client closes the connection server should close the communication with that client (socket).
And once again wait for new clients to connect. Server program never exits.
Using fork function rewrite the programs, such that this server can handle multiple client
connections at one time. To test this you need to run simultaneously multiple copies of
client executions. Please log on server machine number of clients it is handled at this time.
PROGRAM
CLIENTPROGRAM
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<sys/types.h>
#define MAXLINE 20
#define SERV_PORT 5777
main(int argc,char *argv)
{
char sendline[MAXLINE],revline[MAXLINE];
int sockfd;
struct sockaddr_in servaddr;
sockfd=socket(AF_INET,SOCK_STREAM,0);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_port=ntohs(SERV_PORT);
connect(sockfd,(struct sockaddr*)&servaddr,sizeof(servaddr));
printf("\n enter the data to be send");
26 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
while(fgets(sendline,MAXLINE,stdin)!=NULL)
{
write(sockfd,sendline,strlen(sendline));
printf("\n line send");
read(sockfd,revline,MAXLINE);
printf("\n reverse of the given sentence is :
%s",revline); printf("\n");
}
exit(0);
}
SERVERPROGRAM
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<sys/types.h>
#define MAXLINE 20
#define SERV_PORT 5777
main(int argc,char *argv)
{
int i,j;
ssize_t n;
char line[MAXLINE],revline[MAXLINE];
int listenfd,connfd,clilen;
struct sockaddr_in servaddr,cliaddr;
listenfd=socket(AF_INET,SOCK_STREAM,0);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(SERV_PORT);
bind(listenfd,(struct
sockaddr*)&servaddr,sizeof(servaddr)); listen(listenfd,1);
for( ; ; )
{
clilen=sizeof(cliaddr);
connfd=accept(listenfd,(struct sockaddr*)&cliaddr,&clilen);
printf("connect to client");
while(1)
{
if((n=read(connfd,line,MAXLINE))==0)
break;
27 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
line[n-
1]='\0'; j=0;
for(i=n-2;i>=0;i--)
revline[j++]=line[i];
revline[j]='\0';
write(connfd,revline,n);
}
}
}
OUTPUT
28 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
WEEK-6
DESCRIPTION:
Socket function:
#include <sys/socket.h>
int socket int family, int type, int protocol);
Family Description
Type Description
The protocol argument to the socket function is set to zero except for raw sockets.
Connect function: The connect function is used by a TCP client to establish a connection with a TCP
server.
int connect(int sockfd, const struct sockaddr *servaddr, socklen_t addrlen);
Bind function: The bind function assigns a local protocol address to a socket.
int bind(int sockfd, const struct sockaddr *myaddr, s ocklen_t addrlen);
Bzero: It sets the specified number of bytes to 0(zero) in the destination. We often use this function to
initialize a socket address structure to 0(zero).
#include<strings.h>
void bzer(void *dest,size_t nbytes);
Memset: It sets the specified number of bytes to the value c in the destination.
#include<string.h>
void *memset(void *dest, int c, size_t len);
29 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
Close function: The normal UNIX close function is also used to close a socket and terminate a TCP
connection.
#include<unistd.h>
int close(int sockfd);
Return 0 if ok, -1 on error.
Listen function: The second argument to this function specifies the maximum number of connection
that the kernel should queue for this socket.
int listen(int sockfd, int backlog);
Accept function: The cliaddr and addrlen argument are used to ret urn the protocol address of the
connected peer processes (client)
30 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
Pseudo code:
Server side Filer Transfer TCP Pseudo code:
START
Start the program.
Declare the variables and structure for the socket.
Create a socket using socket functions
The socket is binded at the specified port.
Using the object the port and address are declared.
After the binding is executed the file is specified. Then
the file is specified.
Execute the client program.
END
Client side File Transfer TCP Pseudo code:
START
Start the program.
Declare the variables and structure.
Socket is created and connects function is executed.
If the connection is successful then server sends the message.
The file name that is to be transferred is specified in the client side.
The contents of the file is verified from the server side.
END
31 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
SERVERPROGRAM
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<sys/types.h>
#define MAXLINE 20
int i,j;
ssize_t n;
FILE *fp;
char ch;
char line[MAXLINE],recline[MAXLINE];
int listenfd,connfd,clilen;
listenfd=socket(AF_INET,SOCK_STREAM,0);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(SERV_PORT);
bind(listenfd,(struct sockaddr*)&servaddr,sizeof(servaddr));
listen(listenfd,1);
for( ; ; )
{
32 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
clilen=sizeof(cliaddr);
connfd=accept(listenfd,(struct sockaddr*)&cliaddr,&clilen);
printf("connect to client");
while(1)
if((n=read(connfd,line,MAXLINE))==0)
break;
line[n-1]='\0';
fp =
fopen(line,"r");
ch=fgetc(fp);
printf("\n");
while(ch!=EOF) {
printf("%c",ch);
ch=fgetc(fp);
} fcloseall();
write(connfd,line,n)
SERVEROUTPUT:
Connect to client:
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<sys/types.h>
#define MAXLINE 20
char sendline[MAXLINE],recline[MAXLINE];
int sockfd;
sockfd=socket(AF_INET,SOCK_STREAM,0);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_port=ntohs(SERV_PORT);
connect(sockfd,(struct sockaddr*)&servaddr,sizeof(servaddr));
while(fgets(sendline,MAXLINE,stdin)!=NULL)
write(sockfd,sendline,strlen(sendline));
read(sockfd,recline,MAXLINE);
printf("\n");
exit(0);
}
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
CLIENTOUTPUT
33 Dept CEoS
File transferred.
Completed test.txt
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
WEEK-7
AIM: Design a TCP concurrent server to convert a given text into upper case using
multiplexing system call "select".
Description:
Client sends message to server using sent functions. Server receives all the messages. The
select function allows the process to instruct the kernel to wait for any one of multiple events to
occur and to wake up the process onlywhen one or more of these events occurs or when a specified
amount of time has passed.
The select () and poll () methods can be a powerful tool when you're multiplexing network
sockets. Specifically, these methods will indicate when a procedure will be safe to execute
on an open file descriptor without any delays. For instance, a programmer can use these calls to
know when there is data to be read on a socket. By delegating responsibility to
select() and poll(), you don't have to constantly check whether there is data to be read.
Instead, select() and poll() can be placed in the background by the operating system and
woken up when the event is satisfied or a specified timeout has elapsed.
This process can significantly increase execution efficiency of a program. (If you are more
concerned with performance than portability, we discuss some alternatives to select() and
poll()toward the end of the article.)
select( ) description The Single UNIX Specification, version 2 (SUSv2) defines select() as
follows:
int select(int nfds,fd_set *readfds, fd_set *writefds, fd_set *errorfds, struct timeval
*timeout); It takes these parameters:
• int nfds - The highest file descriptor in all given sets plus one
• fd_set *readfds - File descriptors that will trigger a return when data is ready to be read
• fd_set *writefds - File descriptors that will trigger a return when data is ready to be written
to
• fd_set *errorfds - File descriptors that will trigger a return when an exception occurs
• struct timeval *timeout - The maximum period select() should wait for an event
34 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
The return value indicates the number of file descriptors (fds) whose request event has
been satisfied. You can't modify the fd_set structure by changing its value directly. The only
portable way to either set or retrieve the value is by using the provided FD_* macros:
START
Call memeset system call to set the no of bytes to the value in the destination
Set server_addr.sin_family=AF_INET
Set server_addr.sin_port=htons(50000)
Set server_addr.sin_addr.s_addr=htonl(INADDR_ANY)
Call bzero system call to set the specified no of bytes to 0
If bind system call returns -1
then
Perror unable to
bind Exit
35 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
End if
Call listen system
call Set maxfd =
sockfd Set maxi=-1
Loop
form 0 to less than fd_setsize
Set client[i]=-1
Call FD_ZERO( &all) to initialize the set all bits
off Call FD_SET(sockfd,&all) to turn on sockfd
Print tcp server waiting
While true Set
rset=allset
Call select system call tomonitor multiple file descriptors and assign it to
nready If FD_ISSET system call returns true
Then
Set len=sizeof(client_addr)
Call accept system call to accept the client request and assign it to the
connfd Print I got connection from client
START
PROGRAM
SERVERPROGRAM
#include<stdio.h>
#include<netinet/in.h>
#include<sys/types.h>
#include<string.h>
#include<stdlib.h>
#include<sys/socket.h>
#include<sys/select.h>
#include<unistd.h>
38 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
#define MAXLINE 20
#define SERV_PORT 7134 main(int
argc,char **argv)
{
int i,j,maxi,maxfd,listenfd,connfd,sockfd;
int nread,client[FD_SETSIZE];
ssize_t n;
fd_set rset,allset;
char line[MAXLINE];
socklen_t clilen;
struct sockaddr_in cliaddr,servaddr;
listenfd=socket(AF_INET,SOCK_STREAM,0);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(SERV_PORT);
bind(listenfd,(struct sockaddr*)&servaddr,sizeof(servaddr));
listen(listenfd,1);
maxfd=listenfd;
maxi=-1;
for(i=0;i<FD_SETSIZE;i++)
client[i]=-1;
FD_ZERO(&allset);
FD_SET(listenfd,&allset);
for(; ;)
{
rset=allset;
nread=select(maxfd+1,&rset,NULL,NULL,NULL);
if(FD_ISSET(listenfd,&rset))
{
clilen=sizeof(cliaddr);
connfd=accept(listenfd,(struct
sockaddr*)&cliaddr,&clilen); for(i=0;i<FD_SETSIZE;i++)
if(client[i]<0)
{
client[i]=connfd;
break;
}
if(i==FD_SETSIZE)
{
printf("too many clients");
exit(0);
}
FD_SET(connfd,&allset);
if(connfd>maxfd)
maxfd=connfd;
if(i>maxi)
39 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN & NP Lab
maxi=i;
if(--nread<=0)
continue;
}
for(i=0;i<=maxi;i++)
{
if((sockfd=client[i])<0)
continue;
if(FD_ISSET(sockfd,&rset))
{
if((n=read(sockfd,line,MAXLINE))==0)
{
close(sockfd);
FD_CLR(sockfd,&allset);
client[i]=-1;
}
else
{
printf("line recieved from the client :%s\n",line);
for(j=0;line[j]!='\0';j++)
line[j]=toupper(line[j]);
write(sockfd,line,MAXLINE);
}
if(--nread<=0)
break;
}
}
}
}
OUTPUT:
40 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLab
CLIENT PROGRAM
#include<netinet/in.h>
#include<sys/types.h>
#include<stdio.h>#include<
stdlib.h> #include<string.h>
#include<sys/socket.h>
#include<sys/select.h>
#include<unistd.h>
#define MAXLINE 20
#define SERV_PORT 7134 main(int
argc,char **argv)
{
int maxfdp1;
fd_set rset;
char sendline[MAXLINE],recvline[MAXLINE];
int sockfd;
struct sockaddr_in servaddr;
if(argc!=2)
{
printf("usage tcpcli
<ipaddress>"); return;
}
sockfd=socket(AF_INET,SOCK_STREAM,0);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(SERV_PORT);
inet_pton(AF_INET,argv[1],&servaddr.sin_addr);
connect(sockfd,(struct sockaddr*)&servaddr,sizeof(servaddr));
printf("\n enter data to be send");
while(fgets(sendline,MAXLINE,stdin)!=NULL)
{
write(sockfd,sendline,MAXLINE);
printf("\n line send to server is %s",sendline);
read(sockfd,recvline,MAXLINE);
printf("line recieved from the server %s",recvline);
}
exit(0);
}
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
OUTPUT
Enter data to be send :what is u r name?
line send to server is : what is u r name?
line recieved from the server : WHAT IS U R NAME?
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
WEEK-8
AIM: Design UDP Client and server application to reverse the given input sentence
DESCRIPTION:
UDP provides a connectionless service as there need not be any long-term relationship between a
UDP client and server.
UDP provides a message-oriented interface. Each message is sent as a single UDP segment, which means
that data boundaries are preserved. However, this also means that the maximum size of a UDP
segment depends on the maximum size of an IP datagram. Allowing large UDP segments can cause
problems. Processes sending large segments can result in IP fragmentation, quite often on the sending
computer.
UDP offers the same best-effort delivery as IP, which means that segments can be lost, duplicated,
or corrupted in transit. This is why UDP is suitable for applications such as voice or video that can
tolerate delivery errors. See below for more on UDP problems.
49 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
UDP header
The SOURCE PORT field identifies the UDP process which sent the datagram.
The DESTINATION PORT field identifies the UDP process that will handle the payload.
The MESSAGE LENGTH field includes the 8-byte header and the data, measured on octets.
The CHECKSUM field is optional and stored as zero if not computed (a computed zero is
stored as all ones).
Note that UDP does not provide flow control, error control, or retransmission on receipt of a
bad segment. All it provides is demultiplexing multiple processes using the port numbers.
The UDP Checksum
The 16-bit CHECKSUM field is optional. The sender can choose to compute a checksum or
set the field to zero. The receiver only verifies the checksum if the value is non-zero. Note
that UDP uses ones-complement arithmetic, so a computed zero value is stored as all-ones.
UDPProblems
Since UDP provides only a simple delivery service, almost all of the problems with UDP are related to
delivery problems.
UDP-based applications are prone to failures in a congested or loss-intensive network
because a lost UDP datagram has to be handled by the application.
As an extreme example, consider the Network File System (NFS) which uses UDP for remote
file system access, since it benefits from the low-overhead nature of UDP. NFS typically writes
data in large chunks (often 8 KB blocks), which are then split into IP fragments depending on the
MTU of the underlying topology.
Only when all the fragments have been received at the destination is the IP datagram reassembled
and passed via UDP to the NFS application. If the underlying network loses 10%
- 20% of its datagram's, then NFS will encounter problems, resulting in retransmission of
data and thus providing a sluggish and poor performance.
50 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
UDP SERVER
UDP CLIENT
socket
socket
bind
This is
Sendto recvfrom blocking
call and
waits
Till its
recvfrom receives a
sendto require
from the
client
Close close
2)The client just sends a datagram to the server using the sendto function, which requires the address of
the destination as a parameter.
Similarly, the server does not accept a connection from a client.
3)Instead, the server just calls the recvfrom function, which waits until data arrives from some client.
4)recvfrom returns the protocol address of the client, along with the datagram, so the server can send a
response to the correct client.
We can create UDP socket by specifying the second argument to socket function as SOCK_DGRAM.
51 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
include<sys/socket.h>
ssize_t recvfrom(int sockfd, void *buff, size_t nbytes, int flags,
struct sockaddr *form , socklen_t *addrlen);
ssize-t sendto(int sockfd const void *buff, size_t nbytes, int flags,
const structsockaddr *to, socklen_t addrlen);
52 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
START
PROGRAM
SERVERPROGRAM
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<sys/types.h>
#include<stdlib.h>
53 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
CLIENT PROGRAM
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<sys/types.h>
#include<stdlib.h>
#define SERV_PORT 5839
54 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
#define MAXLINE 20
main(int argc,char **argv)
{
ssize_t n;
struct sockaddr_in servaddr;
char sendline[MAXLINE],recvline[MAXLINE];
int sockfd;
if(argc!=2)
{
printf("usage:<IPADDRESS>");
exit(0);
}
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(SERV_PORT);
inet_pton(AF_INET,argv[1],&servaddr.sin_addr);
sockfd=socket(AF_INET,SOCK_DGRAM,0);
printf("enter the data to be send");
while(fgets(sendline,MAXLINE,stdin)!=NULL)
{
sendto(sockfd,sendline,strlen(sendline),0,(struct
sockaddr*)&servaddr,sizeof(servaddr)); printf("line sent");
n=recvfrom(sockfd,recvline,MAXLINE,0,NULL,NULL);
recvline[n]='\0';
fputs(recvline,stdout);
printf("\n reverse of the sentense is
%s",recvline); printf("\n");
}
exit(0);
}
OUTPUT
Line sent
55 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
WEEK-10
DESCRIPTION:
The UDP client and server are created with the help of DatagramSocket and Datagram
packet classes. If the UDP protocol is used at transport, then the unit of data at the transport layer is called a
datagram and and not a segment. In UDP, no connection is
established. It is the responsibility of an application to encapsulate data in datagrams
(using Datagram classes) before sending it. If TCP is used for sending data, then the data is written directly to the
socket (client or server) and reaches there as a connection exists between them. The datagram sent by the
application using UDP may or may not reach the UDP receiver.
START
57 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
PROGRAM
CLIENT PROGRAM
#include<stdio.h>#inclu
de<string.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<unistd.h> #define
SERV_PORT 6349 main(int
argc,char **argv)
{
char filename[80];
int sockfd;
struct sockaddr_in servaddr;
sockfd=socket(AF_INET,SOCK_DGRAM,0);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(SERV_PORT);
inet_pton(AF_INET,argv[1],&servaddr.sin_addr);
printf("enter the file name");
scanf("%s",filename);
sendto(sockfd,filename,strlen(filename),0,(structsockaddr*)&servaddr,sizeof(servad
dr))
}
OUTPUT OFCLIENT
Client:
enter the file name: npfile
58 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
SERVERPROGRAM
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#define SERV_PORT 6349
main(int argc,char **argv)
{
char filename[80],recvline[80];
FILE *fp;
struct sockaddr_in servaddr,cliaddr;
int clilen,sockfd;
sockfd=socket(AF_INET,SOCK_DGRAM,0);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(SERV_PORT);
bind(sockfd,(struct sockaddr*)&servaddr,sizeof(servaddr));
clilen=sizeof(cliaddr);
recvfrom(sockfd,filename,80,0,(struct
sockaddr*)&cliaddr,&clilen); printf("\n date in the file is \n ");
fp=fopen(filename,"r");
while(fgets(recvline,80,fp)!=NULL)
{
printf("\n %s\n ",recvline);
}
fclose(fp);
}
OUTPUTOFSERVER
Server:
something intresting
59 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
WEEK:9
Aim: Design using poll client server application to multiplex TCP and UDP requests for
converting a given text into upper case.
DESCRIPTION:
#include<poll.h>
int poll ( struct pollfd *fdarray, unsigned long nfds, int timeout);
#include <sys/socket.h>
Int getsockopt (int sockfd, int level, int optname, void *optval, socklen_t *optlen);
Int setsockopt (int sockfd, int level, int optname, void *optval, socklen_t *optlen);
perror socket
exit
60 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
init buffer
receive message
end of server infinite loop
return 0
END
Pseudo code for TCP Client:
START
Declare sock as integer variable
Declare character arryas named fname and op
Declare a file pointer variable named fp
Declare variables named server_addr for sockaddr_in structure
If socket system call returns -1
then
Perror socket
Exit
Call memeset system call to set the no of bytes to the value cin the destination
Set server_addr.sin_family=AF_INET
Set server_addr.sin_port=htons(40000)
Set server_addr.sin_addr.s_addr=inet_addr("127.0.0.1")
While true
Print enter file name
Read fname
Send file to socket
Receive file from the socket
61 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
END
START
Then
Perror
socket Exit
Call memeset system call to set the no of bytes to the value cin the destination
Set server_addr.sin_family=AF_INET
Set server_addr.sin_port=htons(40000)
Set server_addr.sin_addr.s_addr=inet_addr("127.0.0.1")
Then
Perror connect
Exit
62 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
While true
Read fname
Close file
Break
Close socket
Return0
END
PROGRAM
CLIENT PROGRAM
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<unistd.h>
#include<netinet/in.h>
#define MAXLINE 20
#define SERV_PORT 8114 main(int
argc,char **argv)
{
int maxfdp1;
fd_set rset;
char sendline[MAXLINE],recvline[MAXLINE];
63 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
int sockfd;
struct sockaddr_in servaddr;
if(argc!=2)
{
printf("usage tcpcli
<ipaddress>"); return;
}
sockfd=socket(AF_INET,SOCK_STREAM,0);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(SERV_PORT);
inet_pton(AF_INET,argv[1],&servaddr.sin_addr);
connect(sockfd,(struct sockaddr
*)&servaddr,sizeof(servaddr)); printf("\nenter data to be
send:"); while(fgets(sendline,MAXLINE,stdin)!=NULL)
{
write(sockfd,sendline,MAXLINE);
printf("\nline send to server :%s
",sendline); read(sockfd,recvline,MAXLINE);
printf("line received from the server : %s",recvline);
}
exit(0);
}
OUTPUT of CLIENT
Enter data to be send:hello
line send to server :HELLO
line received from the server : HELLO
SERVERPROGRAM
#include<stdio.h>
#include<netinet/in.h>
#include<sys/types.h>
#include<string.h>
#include<stdlib.h>
#include<sys/socket.h>
#include<sys/select.h>
#include<unistd.h>
#define MAXLINE 20
#define SERV_PORT 8114
64 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
for(i=0;i<FD_SETSIZE;i++)
client[i]=-1;
FD_ZERO(&allset);
FD_SET(listenfd,&allset);
for(;;)
{
rset=allset;
nready=select(maxfd+1,&rset,NULL,NULL,NULL);
if(FD_ISSET(listenfd,&rset))
{
clilen=sizeof(cliaddr);
connfd=accept(listenfd,(struct sockaddr
*)&cliaddr,&clilen); for(i=0;i<FD_SETSIZE;i++)
if(client[i]<0)
{
client[i]=connfd;
break;
}
if(i==FD_SETSIZE)
{
printf("too many clients");
exit(0);
}
FD_SET(connfd,&allset);
if(connfd>maxfd)
maxfd=connfd;
if(i>maxi)
65 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
maxi=i; if(--
nready<=0)
continue;
}
for(i=0;i<=maxi;i++)
{
if((sockfd=client[i])<0)
continue;
if(FD_ISSET(sockfd,&rset))
{
if((n=read(sockfd,line,MAXLINE))==0)
{
close(sockfd);
FD_CLR(sockfd,&allset); client[i]=-1;
}
else
{
printf("line received from client:%s\n",line);
for(j=0;line[j]!='\0';j++)
line[j]=toupper(line[j]);
write(sockfd,line,MAXLINE);
}
if(--nready<=0)
break;
}
}
}
}
OUTPUTOFSERVER: