0% found this document useful (0 votes)
130 views82 pages

CN Lab Final Record

The document discusses different data link layer framing methods such as character count, character stuffing, and bit stuffing. It also discusses the cyclic redundancy check (CRC) error detection technique. CRC generates a checksum by dividing the data by a fixed polynomial and transmitting the remainder along with the frame. This checksum can be used at the
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
130 views82 pages

CN Lab Final Record

The document discusses different data link layer framing methods such as character count, character stuffing, and bit stuffing. It also discusses the cyclic redundancy check (CRC) error detection technique. CRC generates a checksum by dividing the data by a fixed polynomial and transmitting the remainder along with the frame. This checksum can be used at the
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 82

DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB

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

Source Code for Character Stuffing:


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

char str [50];


int i;
printf("Enter input string");
gets(str);
printf ("After byte stuffing");
printf("\nIn Sender side \n");
printf("\nDLE STX ");
for (i=0; i< (strlen (str)-1); i++)
{

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

Source Code for Bit Stuffing:

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

char str[50]; int


i,flag=0;
printf("\nEnter input string ");
gets(str);
printf("\nAfter bits stuffing \n");
printf("\nIn Sender side ");
for(i=0;i<strlen(str);i++) {

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.

CRC (Cyclic Redundancy Check)

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 )

Eg: x5 + x4 +x0 = 110001

When this method is used, the sender and the receiver should agree upon a

generator polynomial, G(x) in advance.

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)

so that this check summed frame is divisible by G(x).

Divide M(x) by G(x) using modulo-2 division and subtract the remainder from M(x)

using modulo-2subtraction. let the resultant be called as T(x)

T(x) is passed to the receiver and the receiver divides it by G(x).

If there is a remainder, there has been a transmission error.

Algorithm for computing checksum:

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.

2. Divide M(x) by G(x) using MOD-2 division.

7
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB

3. Subtract the remainder from M(x) using MOD-2 subtraction.

4. The result is the check summed frame to be transmitted.

Eg: frame = 1101011011

G(x) = x4 +x +1 = 10011

è degree = 4

Therefore, frame = 1101011011 + 0000

èM(x) = 11010110110000

Commonly used divisor polynomials are:


CRC 12 : x12 + x11 + x3 + x2 + x + 1
CRC 16 : x16 + x15 + x2 + 1
CRC CCITT : x16 + x12 + x5 +

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:

• CRC can detect all single-bit errors


• CRC can detect all double-bit errors (three 1's)
• CRC can detect any odd number of errors (X+1)
• CRC can detect all burst errors of less than the degree of the polynomial.
• CRC detects most of the larger burst errors with a high probability.
• For example CRC-12 detects 99.97% of errors with a length 12 or more.

Program:

#include <stdio.h> #include


<string.h>#define N strlen(g)
char t[28],cs[28],g[28];
int a,e,c,b; void xor()
{
for(c=1;c<N;c++)
cs[c]=((cs[c]==g[c])?'0':'1');
}
void crc()
{
for(e=0;e<N;e++)
cs[e]=t[e];
do
{
if(cs[0]=='1')
xor();
for(c=0;c<N-1;c++)
cs[c]=cs[c+1];
cs[c]=t[e++];
}while(e<=a+N-1);

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

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

Enter the position where error is to be inserted:3


-----------------------
erroneous data:111011001110001110011110011101001000000100001
error detected

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

indicate the working node

Finally, Destination 'D' is relabeled as D(10,H). The path is (D-H-F-E-B-A) as follows:

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

int shortest_dist(int s,int t,int path[])


{
int i,k,min; struct
state
{
int pre;
int length;
int label;
}state[1024];

struct state *p;

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

if(state[i].label==0 && state[i].length<min)


{
min=state[i].length;
k=i;
}
state[k].label=1;

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

printf("\nEnter Number of nodes(1-8): ");


scanf("%d",&n);

printf("\nEnter Source Vertex(1-8): ");


scanf("%d",&p);

printf("\nEnter Destination vertex(1-8): ");


scanf("%d",&q);

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

printf("\nCost is: %d \n",cost);


}

Output:
Enter Number of nodes(1-8): 7

Enter Source Vertex(1-8): 1

Enter Destination vertex(1-8): 7


G-> E-> B-> A->
Cost is: 6

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:

Each node constructs a one-dimensional array containing the "distances"(costs) to all


other nodes and distributes that vector to its immediate neighbors.

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.

Information Distance to Reach Node


Stored at Node
B C D E F G
A

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

Table 1. Initial distances stored at each node(global view).


We can represent each node's knowledge about the distances to all other nodes as a table like
the one given in Table 1.
Note that each node only knows the information in one row of the table.

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

Information Distance to Reach Node


Stored at Node
B C D E F G
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

Table 2. final distances stored at each node ( global view).


In practice, each node's forwarding table consists of a set of triples of the form:
( Destination, Cost, NextHop).

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

Destination Cost NextHop

1 A
A

1 C
C

2 C
D

2 A
E

2 A
F

3 A
G

Table 3. Routing table maintained at node B.

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:

enter the number of nodes:3


enter the root matrix:
024
504
830
state value for router 1 is

24
DHANEKULA INSTITUTE OF ENGG &TECH CN&NPLAB

node 1 via 1 distance 0


node 2 via 2 distance 2
node 3 via 3 distance 4

state value for router 2 is

node 1 via 1 distance 5


node 2 via 2 distance 0
node 3 via 3 distance 4

state value for router 3 is

node 1 via 1 distance 8


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

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

Figure: a) subnet b) sink tree for router B


A broadcast algorithm makes explicit use of the sink tree for the router initiating the
broadcast. A sink tree is a subset of the subnet that includes all the routers but contains
no loops. If each router knows which of its lines belong to the sink tree, it can copy an
incoming broadcast packet onto all the sink tree lines except the one it arrived on. This
method makes excellent use of bandwidth, generating the absolute minimum number of
packets necessary to do the job. The only problem is that each router must have knowledge
of some sink tree for the method to be applicable.

Program:

#include<stdio.h>
#include<stdlib.h>
#define MAX_NODES 20
#define INFINITY 1000

void run_prim(int i,int num_nodes,int *hops);


int dist[MAX_NODES][MAX_NODES];

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

printf("enter the number of nodes:");


scanf("%d",&num_nodes);
fflush(stdin);
printf("enter the connection matrix, 0 if not connected\n");
printf("otherwise,the distance\n");
for(;i<num_nodes;i++)
{
printf("enter the distances for node num:%d\n",i);
for(j=0;j<num_nodes;j++)
{
if(i==j)
{
dist[i][j]=0;
continue;
}
printf("distance from %d to %d= ",i,j);
scanf("%d",&dist[i][j]);
fflush(stdin);
if(dist[i][j]==0)
dist[i][j]=INFINITY;
}
}

printf("\nenter the root node");


scanf("%d",&i);
run_prim(i,num_nodes,hops);
for(j=0;j<num_nodes;j++)
{
for(i=0;i<hops[j];i++)
printf("->%d",path[j][i]);
printf("\n");
}
return 0;
}
void run_prim(int s,int n,int *hops)
{
struct state
{

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:

enter the number of nodes:4


enter the connection matrix, 0 if not connected otherwise, the distance
enter the distances for node num:0
distance from 0 to 1= 3 distance
from 0 to 2= 2 distance from 0 to
3= 1
enter the distances for node num:1
distance from 1 to 0= 7 distance
from 1 to 2= 6 distance from 1 to
3= 5
enter the distances for node num:2
distance from 2 to 0= 9 distance
from 2 to 1= 8 distance from 2 to
3= 7
enter the distances for node num:3
distance from 3 to 0= 6 distance
from 3 to 1= 5 distance from 3 to
2= 4
enter the root node2

->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 provides a one-way flow of data.

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.

Fig: Pipe in a single process, immediately after fork

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.

The fork system call is called once but it returns twice.

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

/* CREATION OF A ONEWAY PIPE BETWEEN TWO PROCESS */

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

Data received from child through pipe: hello world

/*CREATION OF A TWOWAY PIPE BETWEEN TWO PROCESS*/

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:

Int mknod ( char *pathname, int mode, int dev ) ;

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.

mknod() returns -1 if unsuccessful and 0 (zero) otherwise

mknod("myfifo", S_IFIFO | 0644 , 0);

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.

Pseudo code for FIFO SERVER:

START

Create a fifo is created by the mknod system


call. Initialize a fifo and set its attributes.
wait for the client request, on request establish a connection using accept
function. fork a child process.
Read the message from the client through the
connection. Display the client I message.
send an acknowledgement message to the client
. Exit the child process.

END

Pseudo code for FIFO CLIENT:

START

Initialize the fifo and set its attributes. sent


message to the server.

END

11 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB

/* INTERPROCESS COMMUNICATION THROUGH FIFO BETWEEN CLIENT AND SERVER


*/

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

/*read from the first pipe*/


n=read(rdfd,buf,50);
buf[n]='\0';//end of line
printf("full duplex server:read from the pipe:%s\n",buf);

/*convert the string to upper


class*/ count=0;
while(count<n)
{
buf[count]=toupper(buf[count]);
count++;
}
/*write the convertor string back to second pipe*/

write(wrfd,buf,strlen(buf));
}
FIFO SERVEROUTPUT:

full duplex server:read from the pipe: hello

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

FIFO CLIENT OUT PUT

enter line of text hello


full duplex client:read from the pipe: HELLO

13 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB

WEEK-2

AIM: Implement file transfer using Message Queue form of IPC

DESCRIPTION:

Char *path Keyt key Msgget() Int id

Ftok() Semget()

Char proj Shmget()

Fig:Generate IPC ids using ftok

#include <sys/types.h>
#include<sys/ipc.h>

Key_t ftok( char *pathname, char proj ) ;

The file <sys/types.h> defines the key_t datatype, which is typically a 32-bit integer.

Ftok converts a pathname and a project identifier to a system V IPC key

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

Msgget Ssystem call:


A new message queue is created or an existing message Queueis accesed with the
msgget system call

Int msgget (key_t key, int msgflag);

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.

int msgsnd (int msqid , struct msgbuf *ptr, int length);

14 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB

msgrcv system call:


A message is read from a message queue using the msgrcv system call.

int msgrcv(int msqid,struct msgbuf *ptr, int length, long msgtype, int flag);

msgctl system call:

the msgctl system call providea a variety of control operations on a message queue .

int msgctl( int msqid, int cmd, struct msqid_ds *buff);

15 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB

Pseudo code:
START
Initialize character array with string.

Create a message Queue by using msgget() system


call. send a message with msgsnd() system call.
Receive the message by using msgrcv() system call.
Print the message.
kill the message queue using msgctl() system call.
END

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;

char buf[50]; key_t val=1234;

msqid=msgget(val,IPC_CREAT|0666);

msgrcv(msqid,buf,sizeof(buf),0,0);

printf("Received file name:%s",buf);

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

int msqid,l; char

buf[50]; key_t

val=1234;

msqid=msgget(val,IPC_CREAT|0666);

printf("Enter file name:");

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

The family specifies the protocol family

Family Description

AF_INET IPV4 protocol IPV6


AF_INET6 protocol
AF_LOCAL unix domain protocol
AF_ROUTE routing sockets
AF_KEY key socket

Type Description

SOCK_STREAM Stream description


SOCK_DGRAM Datagram socket
SOCK_RAW Raw socket

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)

int accept(int sockfd, struct sockaddr *cliaaddr, socklen_t *addrlen);

IPv4 Socket Address Structure:


An IPv4 socket address structure, commonly called an " Internet socket address
structure, " is named sockaddr_in and defined by including the<netinet/in.h> header.

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

Socket functions for elementary TCP client/server

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

Enter the data to be send: cse


Line send
Reverse of the given sentence: esc

28 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB

WEEK-6

AIM: Design TCP client and server application to transfer file

DESCRIPTION:
Socket function:

#include <sys/socket.h>
int socket int family, int type, int protocol);

The family specifies the protocol family

Family Description

AF_INET IPV4 protocol IPV6


AF_INET6 protocol
AF_LOCAL unix domain protocol
AF_ROUTE routing sockets
AF_KEY key socket

Type Description

SOCK_STREAM Stream description


SOCK_DGRAM Datagram socket
SOCK_RAW Raw socket

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)

int accept(int sockfd, struct sockaddr *cliaaddr, socklen_t *addrlen);

IPv4 Socket Address Structure:


An IPv4 socket address structure, commonly called an " Internet socket address
structure, " is named sockaddr_in and defined by including the<netinet/in.h> header.
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);

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

#define SERV_PORT 5777

main(int argc,char *argv)

int i,j;

ssize_t n;

FILE *fp;

char ch;

char line[MAXLINE],recline[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( ; ; )

{
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:

Hello world sample data to display.


DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
CLIENT PROGRAM

#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],recline[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 file name ");

while(fgets(sendline,MAXLINE,stdin)!=NULL)

write(sockfd,sendline,strlen(sendline));

printf("\n file transfered");

read(sockfd,recline,MAXLINE);

printf("\n Completed... : %s",recline);

printf("\n");

exit(0);

}
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB
CLIENTOUTPUT
33 Dept CEoS

Enter file name : test.txt

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:

• FD_ZERO(fd_set *) - Initializes an fd_set to be empty


• FD_CLR(int fd, fd_set *) - Removes the associated fd from the fd_set
• FD_SET(int fd, fd_set *) - Adds the associated fd to the fd_set
• FD_ISSET(int fd, fd_set *) - Returns a nonzero value if the fd is in fd_set
Upon return from select(), FD_ISSET() can be called for each fd in a given set to identify
whether its condition has been met. With the timeout value, you can specify how long
select() will wait for an event. Iftimeout is NULL, select() will wait indefinitely for an event. If
timeout's timevalstructures are set to 0, select() will return immediately rather than wait for any event
to occur. Otherwise, timeout defines how long select() will wait.

Pseudo code for SERVER:

START

Declare sockfd,connfd as integer


variables Declare clint as integer array
Declare len newfd,maxfd,max and I as integer variables
Declare character arrays named as recv_bufand send_buf
Declare rset,allset ae fd_set type
Declare variables named server_addr and client_addr for sockaddr_in
structure Declare n as ssize_t type
If socket system call returns -1
then perror socket Exit

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

Loop from 0 to less than FD_SETSIZE


If client[i] is less than zero
then
Set client[i]=connfd
Break
End if
If I is equal to FD_SETSIZE
Print too many clients
Exit
End if
Call FD_SET system call to set all bits
on If connfd is grater than maxfd
then
Set maxfd=connfd
If I is grater than
maxi then
Set maxi=i
If -nready <=0 then
Continue
End loop
Loop from 0 to less than or equal to maxi
36 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB

If newfd =client[i] is grater than


zero then
Continue
If FD_ISSET returns
true then
If recv system call returns-
1 then
Close newfd
Call FD_CLR system call toclear the
bits Set client[i]=-1
End if
Else
Print text from the client
Set j=string lenth of received
buffer Declare a integer variable k
Loop from 0 to less than j
Call toupper(recv_buff[k]) function and assign it to the
send_buf[k] End loop
Set send_buf to NULL
Print upper case text send_buf
Send the upper case text to client
End if

If -nready is less than or equal to


zero then
Break
End if
End loop
End if
Return0
END

Pseudo code for 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
37 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB

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")
Call bzero system call to set the specified no of bytes to 0
If connect system call returns -1
Then
Perror connect
Exit
While true
Print enter file name
Read fname
Send file to socket
Receive file from the socket
Print the contents in the
file Open file in write mode
Write contents to file
Print file sent
successfully Close file
Break
Close socket
Return 0
END

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:

line recieved from the client: what is u r name?

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.

The User Datagram Protocol


The TCP/IP protocol suite provides two transport protocols, the User Datagram Protocol
(UDP) described in this chapter, and the Transmission Control Protocol (TCP).There are some
fundamental differences between applications written using TCP versus those that use UDP.
These are because of the differences in the two transport layers:
UDP is a connectionless, unreliable, datagram protocol, quite unlike the connection-
oriented, reliable byte stream provided by TCP. UDP is less complex and easier to understand.
The characteristics of UDP are given below.
End-to-end: UDP can identify a specific process running on a computer.
Connectionless: UDP follows the connectionless paradigm (see below).
Message-oriented: Processes using UDP send and receive individual messages called
segments.
Best-effort: UDP offers the same best-effort delivery as IP.
Arbitrary interaction: UDP allows processes to send to and receive from as many other
processes as it chooses.
Operating system independent: UDP identifies processes independently of the local
operating system.

The Connectionless Paradigm


UDP uses a connectionless communication setup. A process using UDP does not need to
establish a connection before sending data and when two processes stop communicating there are no
additional, control messages. Communication consists only of the data segments themselves.
Message-Oriented Interface

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 Datagram Format


UDP provides a way for applications to send encapsulated IP datagram without having to
establish a connection. UDP transmits segments consisting of an 8-byte header followed by
the payload. The format is shown in Figure

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

Fig: socket programming with UDP

1)The client does not establish a connection with the server.

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

sendto and recvfrom functions used to send and receive datagrams

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

Pseudo code for SERVER


START
Define LOCAL_SERVER_PORT 1500
Define MAX_MSG 3000
Declare structure variables for Server socket data
take character buffers to store data
create IPV4 socket by using socket system
call Initialize server socket
if socket system call return -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(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
End if
bind local server port
server infinite loop
receive message
reading file contents reading
data to msg
closing stream
print received message
Send data received from client again to client by reversing
it Close connection
end of server infinite loop
END

52 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB

Pseudo code for 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")
Call bzero system call to set the specified no of bytes to 0
If connect system call returns -1
then
Perror connect
Exit While
true
Print enter file name
Read fname
Send file to socket
Receive file from the socket
Print the contents in the
file Open file in write mode
Write contents to file
Print file sent
successfully Close file
Break
Close socket
Return 0
END

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

#define SERV_PORT 5839


#define MAXLINE 20
main(int argc,char **argv)
{
int i,j;
ssize_t n;
char line[MAXLINE],recvline[MAXLINE];
struct sockaddr_in servaddr,cliaddr; int
sockfd,clilen;
sockfd=socket(AF_INET,SOCK_DGRAM,0);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
servaddr.sin_port=htons(SERV_PORT);
bind(sockfd,(structsockaddr*)&servaddr,sizeof(servaddr));
for( ; ; )
{
clilen=sizeof(cliaddr);
while(1)
{
if((n=recvfrom(sockfd,line,MAXLINE,0,(structsockaddr*)&cliaddr,&clilen))==0)
break;
printf("\n line receivedsuccessfully");
line[n-1]='\0';
j=0;
for(i=n-2;i>=0;i--
)
{
recvline[j++]=line[i];
}
recvline[j]='\0';
sendto(sockfd,recvline,n,0,(struct sockaddr*)&cliaddr,clilen);
}
}
}

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

Enter the data to be send: cse

Line sent

Reverse of the sentence is:esc

55 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB

WEEK-10

AIM: Design UDP Client server to transfer a file

DESCRIPTION:

UDP Client and Server

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.

Pseudo code for SERVER


START
Declare structure variables for Server socket data
take character buffers to store data
create IPV4 socket by using socket system
call Initialize server socket
if socket system call return -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(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
End if
bind local server port
server infinite loop
receive message
56 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB

reading file contents


reading data to msg
closing stream
print received message
Send data received from client again to client by reversing
it Close connection
end of server infinite loop
END

Pseudo code for 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")
Call bzero system call to set the specified no of bytes to 0
If connect system call returns -1
then
Perror connect
Exit
While true
Print enter file name
Read fname
Send file to socket
Receive file from the socket
Print the contents in the
file Open file in write mode
Write contents to file
Print file sent
successfully Close file
Break
Close socket
Return 0
END

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:

data in the file is:

hai this is np lab

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:

Poll is used for multiplexing tcp & udp requests

#include<poll.h>
int poll ( struct pollfd *fdarray, unsigned long nfds, int timeout);

getsockopt and setsockopt Functions

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

Both return : 0 if ok, -1 on error.

1) Sockfd from socket descriptor.


2) The level specifies the code in the system to interpret the option.
3) The optval is a pointer to a variable, can be set true(non-zero) or false(zero). 4) Size of
the third argument variable.

Pseudo code for Server

Define LOCAL_SERVER_PORT 1500


Define MAX_MSG 100
START

Declare structure variables for Server socket data


take character buffers to store data

create IPV4 socket by using socket system call


Initialize server socket

if socket system call return -


1 then

perror socket
exit
60 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB

bind local server


port server infinite
loop while true

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

Call bzero system call to set the specified no of bytes to


0 If connect system call returns -1
then
Perror connect
Exit

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

Print the contents in the file


Open file in write mode
Write contents to file
Print file sent successfully
Close file
Break
Close socket
Return 0

END

Pseudo code for UDP 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")

Call bzero system call to set the specified no of bytes to 0


If connect system call returns -1

Then

Perror connect

Exit
62 Dept CEoS
DHANEKULAINSTITUTE OFENGG&TECH CN&NPLAB

While true

Print enter file name

Read fname

Send file to socket

Receive file from the socket

Print the contents in the file

Open file in write mode

Write contents to file

Print file sent successfully

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

main(int argc,char **argv)


{
int i,j,maxi,maxfd,listenfd,connfd,sockfd;
int nready,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_addr.s_addr=htonl(INADDR_ANY);
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;
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:

line received from client:hello

You might also like