Вы находитесь на странице: 1из 82

COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

DEPARTMENT OF COMPUTER SCIENCE AND


ENGINEERING

PRACTICAL RECORD

COMPUTER NETWORKS & NETWORK PROGRAMMING LAB


III Year- II Semester
T-0 P-3 C-2

CSE III Year-II Sem Page 1


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

SYLLABUS

Objectives:
To teach students practicle orientation of f networking concepts
To teach students various forms of IPC through Unix and socket Programming

PART A

1. Implement the data link layer framing methods such as character stuffing and bit stuffing.
2. Implement on a data set of characters the three CRC polynomials CRC 12, CRC 16 and
CRC CCIP.
3. Implement Dijkstras algorithm to compute the Shortest path thru a graph.
4. Take an example subnet graph with weights indicating delay between nodes. Now obtain
Routing table art each node using distance vector routing algorithm
5. Take an example subnet of hosts. Obtain broadcast tree for it.

PART B

1. Implement the following forms of IPC.


a)Pipes b)FIFO

2. Implement file transfer using Message Queue form of IPC

3. Write a programme to create an integer variable using shared memory concept and
increment the variable

4. simultaneously by two processes. Use senphores to avoid race conditions

5. Design TCP iterative Client and server application to reverse the given input sentence

6. Design TCP iterative Client and server application to reverse the given input sentence

7. Design TCP client and server application to transfer file

8. Design a TCP concurrent server to convert a given text into upper case using
multiplexing system call select

9. Design a TCP concurrent server to echo given set of sentences using poll functions

10. Design UDP Client and server application to reverse the given input sentence

11. Design UDP Client server to transfer a file

12. Design using poll client server application to multiplex TCP and UDP requests for
converting a given text into upper case.

13. Design a RPC application to add and subtract a given pair of integers

CSE III Year-II Sem Page 2


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

PART :A
Week1
Implementation of the data link layer framing methods such as bit stuffing and
character stuffing.

PROGRAM : BIT Stuffing

#include<stdio.h>
#include<string.h>
void main()
{
int a[20],b[30],i,j,k,count,n;
printf("Enter frame length:");
scanf("%d",&n);
printf("Enter input frame (0's & 1's only):");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
i=0;
count=1;
j=0;
while(i<n)
{
if(a[i]==1)
{
b[j]=a[i];
for(k=i+1;a[k]==1 && k<n && count<5;k++)
{
j++;
b[j]=a[k];
count++;
if(count==5)
{
j++;
b[j]=0;
}
i=k;
}
}
else
{
b[j]=a[i];
}
i++;
j++;
}
printf("After stuffing the frame is:");
for(i=0;i<j;i++)
CSE III Year-II Sem Page 3
COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

printf("%d",b[i]);
}

INPUT:
guest-30708q@administrator-W52K55:~$ cd cnnplab
guest-30708q@administrator-W52K55:~/cnnplab$ cc bs.c
guest-30708q@administrator-W52K55:~/cnnplab$ ./a.out
Enter frame length:8
Enter input frame (0's & 1's only):1
1
1
1
1
1
1
1
OUTPUT:
After stuffing the frame is:111110111guest-30708q@administrator-W52K55:~/cnnplab$

PROGRAM : Character Stuffing

#include<stdio.h>
#include<string.h>
void main()
{
char b[100];
int i=0;
printf("Enter the string :\n");
scanf("%s",b);
printf("\n after stuffing:");
printf("DLESTX");
for(i=0;i<strlen(b);i++)
{
if(b[i]=='d'||b[i]=='D')
{
if(b[i+1]=='l'||b[i+1]=='L')
{
if(b[i+2]=='e'||b[i]=='E')
{
printf("DLE");
}
}
}
printf("%c",b[i]);
}
printf("DLEETX");
}
CSE III Year-II Sem Page 4
COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

INPUT:
$ cc cs2.c
guest-30708q@administrator-W52K55:~/cnnplab$ ./a.out
Enter the string :
candle

OUTPUT:
After stuffing:DLESTXcanDLEdleDLEETXguest-30708q@administrator-
W52K55:~/cnnplab$

Week2
Implement on a data set of characters the three CRC polynomials CRC 12, CRC
16 and CRC CCIP.

PROGRAM : CRC

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
void main()
{
int i,j,keylen,msglen;
char input[100],key[30],temp[30],quot[30],rem[30],key1[30];
printf("\nEnter the data :");
gets(input);
printf("\n Enter the value of key");
gets(key);
keylen=strlen(key);
msglen=strlen(input);
strcpy(key1,key);
for(i=0;i<keylen-1;i++)
input[msglen+i]='0';
for(i=0;i<keylen;i++)
temp[i]=input[i];
for(i=0;i<msglen;i++)
{
quot[i]=temp[0];
if(quot[i]=='0')
for(j=0;j<keylen;j++)
key[j]='0';
else
for(j=0;j<keylen;j++)
key[j]=key1[j];

CSE III Year-II Sem Page 5


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

for(j=keylen-1;j>0;j--)
{
if(temp[j]==key[j])
rem[j-1]='0';
else
rem[j-1]='1';
}
rem[keylen-1]=input[i+keylen];
strcpy(temp,rem);
}
strcpy(rem,temp);
printf("\n Quotient is");
for(i=0;i<msglen;i++)
printf("%c",quot[i]);
printf("\n Remainder is");
for(i=0;i<keylen-1;i++)
printf("%c",rem[i]);
printf("\n Final data is");
for(i=0;i<msglen;i++)
printf("%c",input[i]);
for(i=0;i<keylen-1;i++)
printf("%c",rem[i]);

INPUT:
guest-30708q@administrator-W52K55:~/cnnplab$ cc crc.c
guest-30708q@administrator-W52K55:~/cnnplab$ ./a.out

Enter the data :1101011011

Enter the value of key10011

OUTPUT:
Quotient is1100001010
Remainder is1110
Final data is11010110111110guest-30708q@administrator-W52K55:~/cnnplab$ BB^C
guest-30708q@administrator-W52K55:~/cnnplab$

CSE III Year-II Sem Page 6


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

Week3
Implementation of dijkstras algorithm to compute the shortest path thru a graph.

PROGRAM : DIJKSTRA ALGORITHM

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#define infinity 999

void dij(int n,int s,int cost[10][10],int dist[10])


{
int i,j,count,k,flag[10],min;
for(i=1;i<=n;i++)
{
flag[i]=0;
dist[i]=cost[s][i];
}
count=2;
while(count<=n)
{
min=infinity;
for(k=1;k<=n;k++)
if(dist[k]<min && !flag[k])
{
min=dist[k];
j=k;
}
flag[j]=1;
count++;
for(k=1;k<=n;k++)
if((dist[j]+cost[j][k]<dist[k]) && !flag[k])
dist[k]=dist[j]+cost[j][k];
}
}
int main()
{
int n,s,d,i,j,cost[10][10],dist[10];
printf("\n Enter the no.of nodes");
scanf("%d",&n);
printf("\n Enter the cost matrix");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
printf(" Cost of node[%d] to node [%d] is:",i,j);
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
CSE III Year-II Sem Page 7
COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

cost[i][j]=infinity;
}
printf("Enter source node");
scanf("%d",&s);
printf("Enter destination node");
scanf("%d",&d);
dij(n,s,cost,dist);
printf("\n shortest path:\n");
printf("%d->%d,cost=%d\n",s,d,dist[d]);
}

OUTPUT:
guest-30708q@administrator-W52K55:~/cnnplab$ cc DIJKSTRA.C
guest-30708q@administrator-W52K55:~/cnnplab$ ./a.out

Enter the no.of nodes4

Enter the cost matrix Cost of node[1] to node [1] is:999


Cost of node[1] to node [2] is:1
Cost of node[1] to node [3] is:999
Cost of node[1] to node [4] is:2
Cost of node[2] to node [1] is:1
Cost of node[2] to node [2] is:999
Cost of node[2] to node [3] is:3
Cost of node[2] to node [4] is:4
Cost of node[3] to node [1] is:999
Cost of node[3] to node [2] is:3
Cost of node[3] to node [3] is:999
Cost of node[3] to node [4] is:1
Cost of node[4] to node [1] is:2
Cost of node[4] to node [2] is:4
Cost of node[4] to node [3] is:1
Cost of node[4] to node [4] is:999
Enter source node1
Enter destination node4

shortest path:
1->4,cost=2

CSE III Year-II Sem Page 8


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

Week 4
Take an example subnet graph with weights indicating delay between nodes. now
obtain routing table art each node using distance vector routing algorithm
PROGRAM:
#include<stdio.h>
#include<unistd.h>
#include<stdlib.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("\n Enter no.of nodes:");
scanf("%d",&n);
printf("\n Enter the cost matrix:\n");
for(i=0;i<n;i++)
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;

CSE III Year-II Sem Page 9


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

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++)
{
printf("\n State value for router %d is :",i+1);
for(j=0;j<n;j++)
printf("\t\nnode%dvia%d:distance
d",j+1,rt[i].from[j]+1,rt[i].dist[j]);
}

OUTPUT:
guest-30708q@administrator-W52K55:~/cnnplab$ cc DVR.C
guest-30708q@administrator-W52K55:~/cnnplab$ ./a.out

Enter no.of nodes:4

Enter the cost matrix:


0134
1034
2306
0460

CSE III Year-II Sem Page 10


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

State value for router 1 is :


node 1 via 1 :distance 0
node 2 via 2 :distance 1
node 3 via 3 :distance 3
node 4 via 4 :distance 4
State value for router 2 is :
node 1 via 1 :distance 1
node 2 via 2 :distance 0
node 3 via 3 :distance 3
node 4 via 4 :distance 4
State value for router 3 is :
node 1 via 1 :distance 2
node 2 via 2 :distance 3
node 3 via 3 :distance 0
node 4 via 4 :distance 6
State value for router 4 is :
node 1 via 1 :distance 0
node 2 via 1 :distance 1
node 3 via 1 :distance 3
node 4 via 4 :distance 0guest-30708q@administrator-W52K55:~/cnnplab$ ^C
guest-30708q@administrator-W52K55:~/cnnplab$
AIM:Take an example subnet of hosts. Obtain broadcast tree for it.

PROGRAM:

#include <stdio.h>
int p,q,u,v,n;
int min=99,
mincost=0;
int t[50][2],i,j;
int parent[50],edge[50][50];
main()
CSE III Year-II Sem Page 11
COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

{
clrscr();
printf("\n Enter the number of nodes");
scanf("%d",&n);
for(i=0;iedge[i][j])
{
min=edge[i][j];
u=i;
v=j;
}
p=find(u);
q=find(v);
if(p!=q)
{
t[i][0]=u;
t[i][1]=v;
mincost=mincost+edge[u][v];
sunion(p,q);
}
Else
{
t[i][0]=-1;
t[i][1]=-1;
}
min=99;
}
printf("Minimum cost is %d\n Minimum spanning tree is\n" ,mincost);
for(i=0;i0)
l=parent[l];
return l;
}

CSE III Year-II Sem Page 12


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

OUTPUT:
Enter the number of nodes3
A B C
A1234
B1234
C 4567
Minimum cost is 3
Minimum spanning tree is C A 3
PART :B

AIM: Implement the following forms of IPC.


a)Pipes b)FIFO
DESCRIPTION:

Unix Process : An entity that executes a given piece of code, has its own execution stack,
its own set of memory pages, its own file descriptors table, and a unique process ID

The fork() System Call: The fork() system call is the basic way to create a new process.

Prototype: #include <unistd.h>


pid_t fork(void);
This system call causes the current process to be split into two processes - a
parent process, and a child process. All of the memory pages used by the original process
get duplicated during the fork() call, so both parent and child process see the exact same
image. The only distinction is when the call returns. When it returns in the parent process,
its return value is the process ID (PID) of the child process. When it returns inside the
child process, its return value is '0'. If for some reason this call failed (not enough
memory, too many processes, etc.), no new process is created, and the return value of the
call is '-1'. In case the process was created successfully, both child process and parent
process continue from the same place in the code where the fork() call was used.

Using pipes

pipe() system call:


To create a simple pipe with C, we make use of the pipe() system call. It takes a
single argument, which is an array of two integers, and if successful, the array will
contain two new file descriptors to be used for the pipeline. After creating a pipe, the
process typically spawns a new process (remember the child inherits open file
descriptors).

CSE III Year-II Sem Page 13


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

Prototype:
#include <unistd.h>
int pipe( int fd[2] );

Returns: 0 on success
-1 on error

NOTES: fd[0] is set up for reading, fd[1] is set up for writing

read system call : read - read from a file descriptor

Prototype:
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);

read() attempts to read up to count bytes from file descriptor fd into the buffer
starting at buf.

Returns: On success, the number of bytes read is returned (zero indicates end of
file).

write system call: write - write to a file descriptor

Prototype:
#include <unistd.h>

ssize_t write(int fd, const void *buf, size_t count);

write() writes up to count bytes from the buffer pointed buf to the file referred
to by the file descriptor fd.

On success, the number of bytes written is returned (zero indicates nothing was
written). On error, -1 is returned, and errno is set appropriately.

Using FIFO

DESCRIPTION: A FIFO is similar to a pipe. A FIFO (First In First Out) is a one-way


flow of data. FIFOs have a name, so unrelated processes can share the FIFO. FIFO is a
named pipe. This is the main difference between pipes and FIFOs.

Prototype: A FIFO is created by the mkfifo


function: #include <sys/types.h>

CSE III Year-II Sem Page 14


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

#include <sys/stat.h>
int mkfifo(const char *pathname, mode_t mode);

pathname a UNIX pathname (path and filename). The name of the FIFO
mode the file permission bits.
FIFO can also be created by the mknod system call,
e.g., mknod(fifo1, S_IFIFO|0666, 0) is same as mkfifo(fifo1, 0666).

Properties: ( Some of them are also applicable to PIPES)


1) After a FIFO is created, it can be opened for read or write.
2) Normally, opening a FIFO for read or write, it blocks until another process
opens it for write or read.
3) A read gets as much data as it requests or as much data as the FIFO has,
whichever is less.
4) A write to a FIFO is atomic, as long as the write does not exceed the capacity
of the FIFO. The capacity is at least 4k.

Open system call: Given a pathname for a file, open() returns a file descriptor, a small,
nonnegative integer for use in subsequent system calls (read(), write()). The file
descriptor returned by a successful call will be the lowest-numbered file descriptor not
currently open for the process.

Prototype:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int open(const char *pathname, int flags);
Close system call: delete a descriptor

Prototype:

#include <unistd.h>

int close(int fildes);


PROGRAM: pipe()

CSE III Year-II Sem Page 15


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

#include<stdio.h>

#include<unistd.h>

#include<stdlib.h>

main()

int pid[2];

char buf[6];

if(pipe(pid)==-1)

perror("Error");

exit(2);

switch(fork())

case -1: perror("Fork Failed");

break;

case 0:

printf("Child - writing");

write(pid[1],"MY PIPE",6);

printf("Child Exited\n");

break;

default:

printf("parent - Reading");

read(pid[0],buf,6);

printf("%s",buf);

break;

OUTPUT:
CSE III Year-II Sem Page 16
COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

administrator@administrator-Veriton-Series:~/cnnplab$ cc pipe1.c

administrator@administrator-Veriton-Series:~/cnnplab$ ./a.out

Child - writingChild Exited

parent - ReadingMY PIPE

administrator@administrator-Veriton-Series:~/cnnplab$

PROGRAM: FIFO

#include<stdio.h>

#include<stdlib.h>

#include<errno.h>

#include<string.h>

#include<fcntl.h>

#include<sys/types.h>

#include<sys/stat.h>

#include<unistd.h>

#define FIFO_NAME "xyz"

main()

char s[300];

int num,fd;

mknod(FIFO_NAME, S_IFIFO | 0666, 0);

switch(fork())

case -1: perror("Error\n");

exit(1);

case 0:fd=open(FIFO_NAME, O_WRONLY);

printf("Get a reader - type some information\n" );

CSE III Year-II Sem Page 17


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

while(scanf("%s",s),!feof(stdin))

if((num=write(fd,s,strlen(s)))==-1)

perror("Error\n");

else

printf("Speak : wrote %d bytes\n",num);

break;

default:

printf("Waiting for Writers\n");

fd=open(FIFO_NAME, O_RDONLY);

printf("Get a Writer :%d\n",fd );

do

if((num=read(fd,s,300))==-1)

perror("Error\n");

else

s[num]='\0';

printf("Tick : read %d bytes: %s\n", num,s);

}while(num>0);

break;

OUTPUT:

CSE III Year-II Sem Page 18


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

administrator@administrator-Veriton-Series:~/cnnplab$ cc fifo1.c

administrator@administrator-Veriton-Series:~/cnnplab$ ./a.out

Waiting for Writers

Get a Writer :3

Get a reader - type some information

hi

Speak : wrote 2 bytes

Tick : read 2 bytes: hi

welcome

Speak : wrote 7 bytes

Tick : read 7 bytes: welcome

^C

administrator@administrator-Veriton-Series:~/cnnplab$

AIM: Implement file transfer using Message Queue form of IPC.

DESCRIPTION:
Message queues provide an asynchronous communications protocol, meaning that
the sender and receiver of the message do not need to interact with the message queue at
the same time. Messages placed onto the queue are stored until the recipient retrieves
them. Message queues have implicit or explicit limits on the size of data that may be
transmitted in a single message and the number of messages that may remain outstanding
on the queue.
IMPLEMENTATION:
Message buffer:
The first structure we'll visit is the msgbuf structure. This particular data structure can be
thought of as a template for message data. While it is up to the programmer to define
structures of this type, it is imperative that you understand that there is actually a
structure of type msgbuf. The structure is as follws:
#include<sys/ipc.h>

CSE III Year-II Sem Page 19


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

#include<sys/msg.h>

/* message buffer for msgsnd and msgrcv calls */


struct msgbuf {
long mtype; /* type of message */
char mtext[1]; /* message text */
};

There are two members in the msgbuf structure:

mtype : The message type, represented in a positive number. This must be a


positive number.
mtext :The message data itself.

msgget() system call:


Prototype:
#include <sys/types.h>
#include <sys/ipc.h>
#include
<sys/msg.h>
int msgget(key_t key, int msgflg);
DESCRIPTION:
The msgget() system call returns the message queue identifier associated with the value
of the key argument. A new message queue is created if key has the value
IPC_PRIVATE or key isn't IPC_PRIVATE, no message queue with the given key key
exists, and IPC_CREAT is specified in msgflg. If msgflg specifies both IPC_CREAT and
IPC_EXCL and a message queue already exists for key, then msgget() fails with errno set
to EEXIST.
If successful, the return value will be the message queue identifier (a nonnegative
integer), otherwise -1 with errno indicating the error.

msgsnd() & msgrcv() system


call: Prototype:

int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);

ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long


msgtyp, int msgflg);
CSE III Year-II Sem Page 20
COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

DESCRIPTION: The msgsnd() and msgrcv() system calls are used, respectively, to
send messages to, and receive messages from, a message queue. The calling process must
have write permission on the message queue in order to send a message, and read
permission to receive a message.

msgsnd() parameters:
msqid : (Input) Message queue identifier, a positive integer. It is returned by the
msgget() function and used to identify the message queue to send the message to.

msgp : (Input) Pointer to a buffer with the message to be sent. See above for the details
on the format of the buffer.

msgsz : (Input) Length of the data part of the message to be sent.


msgflg: (Input) Operations flags. The value of msgflg is either zero or is obtained
by performing an OR operation on one or more of the following constants:
IPC_NOWAIT :If the message queue is full, do not wait for space to become
available on the message queue and return immediately.

Return Values: The msgsnd() function returns the value 0 if successful; otherwise
the value -1 is returned.

msgrcv() parameters:

msqid: (Input) Message queue identifier, a positive integer. It is returned by the msgget()
function and used to identify the message queue to receive the message from. msgp
:(Output) Pointer to a buffer in which the received message will be stored. See above for
the details on the format of the buffer.
msgsz:(Input) Length of the data part of the buffer.
msgtyp:(Input) Type of message to be received.
msgflg:(Input) Operations flags. The value of msgflg is either zero or is obtained
by performing an OR operation on one or more of the following constants:
IPC_NOWAIT: If a message is not available, do not wait for the message
and return immediately.

CSE III Year-II Sem Page 21


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

MSG_NOERROR: If the data part of the message is larger than msgsz, do


not return an error.

Return Values:

Value: msgrcv() was successful. The value returned is the number of bytes of
data placed in the data part of the buffer pointed to by the msgp parameter.

-1: msgrcv() was not successful.

PROGRAM:
PROCESS1:

#include<stdio.h>

#include<errno.h>

#include<string.h>

#include<stdlib.h>

#include<sys/types.h>

#include<fcntl.h>

#include<unistd.h>

#include<sys/ipc.h>

#include<sys/msg.h>

struct msgbuf

long mtype;

char mtext[1];

};

main()

char s[80];

int rc;

int q_id=msgget(123, IPC_CREAT | 0644);

CSE III Year-II Sem Page 22


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

printf("%d",q_id);

while(1)

struct msgbuf* rcv=(struct msgbuf*)malloc(sizeof(struct msgbuf*)+120);

rc=msgrcv(q_id,rcv,80,0,MSG_NOERROR);

if(rc<1)

perror("Main: msgrcv\n");

exit(1);

printf("Type:%ld --- Data: %s\n",rcv->mtype,rcv->mtext);

PROCESS2:

#include<stdio.h>

#include<errno.h>

#include<string.h>

#include<stdlib.h>

#include<sys/types.h>

#include<fcntl.h>

#include<unistd.h>

#include<sys/ipc.h>

#include<sys/msg.h>

struct msgbuf

long mtype;

CSE III Year-II Sem Page 23


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

char mtext[1];

};

main()

char s[80];

int q_id=msgget(123, IPC_CREAT | 0644);

FILE *fp;

struct msgbuf* msg=(struct msgbuf*)malloc(sizeof(struct msgbuf*)+80);

fp=fopen("pipe1.c","r");

if(q_id==-1)

perror("msgget(): Error\n");

exit(1);

printf("Message Queu Created with ID : %d\n", q_id);

while(fgets(s,80,fp)!=NULL)

msg->mtype=1;

strcpy(msg->mtext,s);

msgsnd(q_id,msg,strlen(s),0);

sleep(2);

OUTPUT:

Note: To send a desired file,we need to run a process2.c then process1.c .

administrator@administrator-Veriton-Series:~/cnnplab$ cc process2.c -o s1

CSE III Year-II Sem Page 24


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

administrator@administrator-Veriton-Series:~/cnnplab$ ./s1

0 Type:1 --- Data: #include<stdio.h>

Type:1 --- Data: #include<unistd.h>

Type:1 --- Data: #include<stdlib.h>

Type:1 --- Data: main()

Type:1 --- Data: {

Type:1 --- Data: int pid[2];

Type:1 --- Data: char buf[6];

Type:1 --- Data: if(pipe(pid)==-1)

Type:1 --- Data: {

Type:1 --- Data: perror("Error");

Type:1 --- Data: exit(2);

Type:1 --- Data: }

Type:1 --- Data: switch(fork())

Type:1 --- Data: {

Type:1 --- Data: case -1: perror("Fork Failed");

Type:1 --- Data: break;

Type:1 --- Data: case 0:

Type:1 --- Data: printf("Child - writing");

Type:1 --- Data: write(pid[1],"MY PIPE",6);

Type:1 --- Data: printf("Child Exited\n");

Type:1 --- Data: break;

Type:1 --- Data: default:

Type:1 --- Data: printf("parent - Reading");

Type:1 --- Data: read(pid[0],buf,6);

Type:1 --- Data: printf("%s",buf);

CSE III Year-II Sem Page 25


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

Type:1 --- Data: break;

Type:1 --- Data: }

Type:1 --- Data: }

process2:

administrator@administrator-Veriton-Series:~/cnnplab$ cc process1.c -o s2

administrator@administrator-Veriton-Series:~/cnnplab$ ./s2

Message Queu Created with ID : 0

administrator@administrator-Veriton-Series:~/cnnplab$ ^C

administrator@administrator-Veriton-Series:~/cnnplab$

AIM: Write a program to create an integer variable using shared memory concept
and increment the variable simultaneously by two processes. Use semaphores to
avoid race conditions

DESCRIPTION:
Multithreaded applications are part and parcel of day-to-day commercial
application. It would be difficult to imagine any full fledged application running
commercially that is not multithreaded. Applications must use the multithreaded
approach to improve on the performance of the application or systems. However, most
beautiful things in life do not come without a price. Likewise, if the multithreaded feature
needs to be used by the application, then it comes with a set of issues, such as deadlocks,
race conditions, incorrect behavior of threads, etc. To overcome these issues, the OS
provides a set of tools like Mutex, semaphores, signals and barriers that are handy in
solving multithreaded multiprocessed issues. This article discusses one of these tool,
semaphores, and provides some insight about them.

Semaphores can be thought of as simple counters that indicate the status of a


resource. This counter is a protected variable and cannot be accessed by the user directly.
The shield to this variable is provided by none other than the kernel. The usage of this
semaphore variable is simple. If counter is greater that 0, then the resource is available,
and if the counter is 0 or less, then that resource is busy or being used by someone else.

CSE III Year-II Sem Page 26


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

This simple mechanism helps in synchronizing multithreaded and multiprocess based


applications. Semaphores were invented and proposed by Edsger Dijkstra, and still used
in operating systems today for synchronization purposes.

Semaphores can be either binary or counting, depending on the number of shared


resources. If a single shared resource is used, then we would require just one semaphore
for synchronization purposes. In that case, the semaphore is referred as a binary
semaphore. In all other cases, where the number of resources shared across users are
greater than one, you would use multiple semaphores, in which case they are

referred as counting semaphores.

Semaphores basically implement two kinds of operations. One to wait on the


semaphore variable and another that signals the semaphore variable.

IMPLEMENTATION:

semget() system call: get a semaphore set identifier


Prototype:
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>

int semget(key_t key, int nsems, int semflg);

DESCRIPTION: The semget() system call returns the semaphore set identifier
associated with the argument key. A new set of nsems semaphores is created if key has
the value IPC_PRIVATE or if no existing semaphore set is associated with key and
IPC_CREAT is specified in semflg.

If semflg specifies both IPC_CREAT and IPC_EXCL and a semaphore set


already exists for key, then semget() fails with errno set to EEXIST.

Upon creation, the least significant 9 bits of the argument semflg define the
permissions (for owner, group and others) for the semaphore set.

semop() system call: semaphore operations

Prototype:

CSE III Year-II Sem Page 27


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

int semop(int semid, struct sembuf *sops, unsigned nsops);

If successful semop()return 0; otherwise they return -1 with errno indicating


the error.
The first argument to semget() is the key value (in our case returned by a call to
semget). The second argument (sops) is a pointer to an array of operations to be

performed on the semaphore set, while the third argument (nsops) is the number of
operations in that array.

The sops argument points to an array of type sembuf. This structure is declared in
sys/sem.h as follows:

/* semop system call takes an array of these */


struct sembuf {
ushort sem_num; /* semaphore index in array */
short sem_op; /* semaphore operation */
short sem_flg; /* operation flags */
};

sem_num :The number of the semaphore you wish to deal with


sem_op : The operation to perform (positive, negative, or zero) sem_flg
: There are two control flags that can be used with semop().
IPC_NOWA
IT
SEM_UND
O

semctl() system call:


The semctl system call is used to perform control operations on a semaphore set.
Prototype:
int semctl ( int semid, int semnum, int cmd, union semun arg );
returns positive integer on success

CSE III Year-II Sem Page 28


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

The first argument to semctl() is the key value (in our case returned by a call to
semget). The second argument semnum is the semaphore number that an operation is
targeted towards. In essence, this can be thought of as an index into the semaphore set,
with the first semaphore (or only one) in the set being represented by a value of zero
(0).

The cmd argument represents the command to be performed against the set. As
you can see, the familiar IPC_STAT/IPC_SET commands are present, along with a
wealth of additional commands specific to semaphore sets:
IPC_STAT: Retrieves the semid_ds structure for a set, and stores it in the address of the
buf argument in the semun union.
IPC_SET : Sets the value of the ipc_perm member of the semid_ds structure for a
set. Takes the values from the buf argument of the semun union.
IPC_RMID: Removes the set from the kernel.
GETVAL : Returns the value of a single semaphore within the set.
SETALL: Sets all semaphore values with a set to the matching values contained in
the array member of the union.
SETVAL : Sets the value of an individual semaphore within the set to the val member of
the union.

The arg argument represents an instance of type semun. This particular union is
declared in linux/sem.h as follows:

/* arg for semctl system calls. */


union semun {
int val; /* value for SETVAL */
struct semid_ds *buf; /* buffer for IPC_STAT & IPC_SET */
ushort *array; /* array for GETALL & SETALL */
struct seminfo *__buf; /* buffer for IPC_INFO
*/ void *__pad;
};

CSE III Year-II Sem Page 29


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

val :Used when the SETVAL command is performed. Specifies the value to
set the semaphore to.
buf : Used in the IPC_STAT/IPC_SET commands. Represents a copy of
the internal semaphore data structure used in the kernel.
Array: A pointer used in the GETALL/SETALL commands. Should point to
an array of integer values to be used in setting or retrieving all
semaphore values in a set.
Shared Memory:

Shared Memory is an efficeint means of passing data between programs. One program will
create a memory portion which other processes (if permitted) can access.

System calls:

shmget(): is used to obtain access to a shared memory segment.

int shmget(key_t key, size_t size, int shmflg);

The key argument is a access value associated with the semaphore ID. The size
argument is the size in bytes of the requested shared memory. The shmflg argument
specifies the initial access permissions and creation control flags.

When the call succeeds, it returns the shared memory segment ID. This call is
also used to get the ID of an existing shared segment (from a process requesting sharing
of some existing memory portion).

shmctl(): shmctl() is used to alter the permissions and other characteristics of a shared
memory segment.

int shmctl(int shmid, int cmd, struct shmid_ds *buf);

The process must have an effective shmid of owner, creator or superuser to


perform this command. The cmd argument is one of following control commands:

SHM_LOCK : Lock the specified shared memory segment in memory. The


process must have the effective ID of superuser to perform this
command.
CSE III Year-II Sem Page 30
COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

SHM_UNLOCK : Unlock the shared memory segment. The process must have
the effective ID of superuser to perform this command.
IPC_STAT : Return the status information contained in the control structure and place it
in the buffer pointed to by buf. The process must have read permission on
the segment to perform this command.
IPC_SET : Set the effective user and group identification and access permissions. The
process must have an effective ID of owner, creator or superuser to Perform this
command.
IPC_RMID : Remove the shared memory segment.

Attaching and Detaching a Shared Memory Segment :


shmat() and shmdt() are used to attach and detach shared memory segments.
They are prototypes as follows:
void *shmat(int shmid, const void *shmaddr, int shmflg);
int shmdt(const void *shmaddr);
shmat() returns a pointer, shmaddr, to the head of the shared segment associated
with a valid shmid. shmdt() detaches the shared memory segment located at the address
indicated by shmaddr

PROGRAM:

#include<stdio.h>

#include<errno.h>

#include<string.h>

#include<stdlib.h>

#include<sys/types.h>

#include<sys/stat.h>

#include<sys/ipc.h>

#include<sys/shm.h>

#include<sys/sem.h>

void executeProcess(int);

CSE III Year-II Sem Page 31


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

#define SEM_ID 250

int* cnt=0;

main()

int shmid;

char* shm_addr;

int i;

int sem_set_id; /* ID of the semaphore Set*/

shmid=shmget(1,getpagesize(),IPC_CREAT | 0644);

shm_addr=shmat(shmid, 0,SHM_RND);

/* Creating a the variable on shared memory segment*/

cnt=(int *)shm_addr;

sem_set_id=semget(SEM_ID,1,IPC_CREAT | 0600);

semctl(sem_set_id,0,SETVAL,1);

switch(fork())

case -1:perror("Error on Fork");

exit(2);

case 0:

i=0;

while(i<10)

sleep(1);

printf("Child:");

executeProcess(sem_set_id);

i++;

CSE III Year-II Sem Page 32


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

break;

default:

i=0;

while(i<10)

sleep(1);

printf("Parent :");

executeProcess(sem_set_id);

i++;

break;

void executeProcess(int sem_set_id)

/*Structure for Semaphore Operations*/

struct sembuf sem_op;

/* If the value is 1, decrement and proceed*/

sem_op.sem_num=0;

sem_op.sem_op=-1;

sem_op.sem_flg=0;

/* Lock the Shared Memory*/

semop(sem_set_id,&sem_op,1);

printf("%d\n",(*cnt)++);

/* Finally Signal the Semaphore - to increase its value by one */

CSE III Year-II Sem Page 33


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

sem_op.sem_num=0;

sem_op.sem_op=1;

sem_op.sem_flg=0;

/* Unlock the Shared Memory*/

semop(sem_set_id,&sem_op,1);

OUTPUT:

administrator@administrator-Veriton-Series:~/cnnplab$ cc sm.c

administrator@administrator-Veriton-Series:~/cnnplab$ ./a.out

Parent :0

Child:1

Child:2

Parent :3

Parent :4

Child:5

Child:6

Parent :7

Child:8

Parent :9

Parent :10

Child:11

Parent :12

Child:13

Parent :14

Child:15

Parent :16

CSE III Year-II Sem Page 34


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

Child:17

Parent :18

Child:19

administrator@administrator-Veriton-Series:~/cnnplab$

Week 4

AIM: Design TCP iterative server and client application to reverse the given
input sentence.

DESCRIPTION: Iterative servers process one request at a time

Steps are required on server side:

1. Create a socket with the socket() system call.


2. Bind the socket to an address using the bind() system call. For a server socket on
the Internet, an address consists of a port number on the host machine.
3. Listen for connections with the listen() system call.
4. Accept a connection with the accept() system call. This call typically blocks until
a client connects with the server.
5. Send and receive data using the read() and write() system calls.

Steps are required on client side:

1. Create a socket with the socket() system call.


2. Connect the socket to the address of the server using the connect() system call.
3. Send and receive data. There are a number of ways to do this, but the simplest is
to use the read() and write() system calls.

socket() System Call: Sockets allow communication between two different processes on
the same or different machines. To be more precise, it's a way to talk to other computers
using standard Unix file descriptors. In Unix, every I/O actions are done by writing or
reading to a file descriptor. A file descriptor is just an integer associated with an open file
and it can be a network connection, a text file, a terminal, or something else.

Prototype:

#include <sys/types.h>
#include <sys/socket.h>
CSE III Year-II Sem Page 35
COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

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

family is usually set to AF_INET

type is set to one of:

SOCK_STREAM stream socket connection oriented


SOCK_DGRAM datagram socket connectionless

protocol is almost always set to 0

Return Value: Upon successful completion, socket() shall return a non-negative integer,
the socket file descriptor. Otherwise, a value of -1 shall be returned and errno set to
indicate the error.

bind() System Call:- bind a name to a socket

Prototype:

#include <sys/socket.h>

int bind(int socket, const struct sockaddr


*address, socklen_t address_len);

The bind() function shall assign a local socket address address to a socket identified by
descriptor socket that has no local socket address assigned. Sockets created with the
socket() function are initially unnamed; they are identified only by their address family.

The bind() function takes the following arguments:

Socket - Specifies the file descriptor of the socket to be bound.

address- Points to a sockaddr structure containing the address to be bound to


the socket. The length and format of the address depend on the address family
of the socket.

address_len - Specifies the length of the sockaddr structure pointed to by the


address argument.

Return Value: Upon successful completion, bind() shall return 0; otherwise, -1 shall
be returned and errno set to indicate the error.

listen() System Call:- listen for socket connections and limit the queue of incoming
connections

CSE III Year-II Sem Page 36


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

Prototype: #include <sys/socket.h>

int listen(int socket, int backlog);

The listen() function shall mark a connection-mode socket, specified by the socket
argument, as accepting connections.

The second parameter backlog specifies the number of requests that can be
queued by the system before the server executes the accept system call.

Return Value: Upon successful completions, listen() shall return 0; otherwise, -1 shall
be returned and errno set to indicate the error.

accept() system call: The system call accept is used by connection-oriented server to set
up an actual connection with a client process.

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

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

Return value: Upon successful completion, accept() shall return the non-negative file
descriptor of the accepted socket. Otherwise, -1 shall be returned and errno set to indicate
the error.

connect() system call: The system call connect is used by a client to establish a
connection with the server.

Prototype:

#include <sys/socket.h>
int connect(int socket, const struct sockaddr *address, socklen_t address_len);

The connect() function shall attempt to make a connection on a socket. The function
takes the following arguments:

socket - Specifies the file descriptor associated with the socket.

address - Points to a sockaddr structure containing the peer address. The length and
format of the address depend on the address family of the socket.

address_len - specifies the length of the sockaddr structure pointed to by the


address argument.

Return Value : Upon successful completion, connect() shall return 0; otherwise, -1


shall be returned and errno set to indicate the error.

CSE III Year-II Sem Page 37


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

PROGRAM:
server.c

#include<stdio.h>

#include<sys/types.h>

#include<sys/socket.h>

#include<netinet/in.h>

#include<strings.h>

#include<stdlib.h>

#include<string.h>

#include<time.h>

void str_echo(int);

int main()

int listenfd, connfd,n,clilen;

struct sockaddr_in servaddr,cliaddr;

char buff[300];

listenfd =socket(AF_INET, SOCK_STREAM,0);

bzero(&servaddr, sizeof(servaddr));

servaddr.sin_family=AF_INET;

servaddr.sin_addr.s_addr=inet_addr("127.0.0.1");//htonl(INADDR_ANY);

servaddr.sin_port=htons(9000);

bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr));

listen(listenfd,10);

for(;;)

clilen=sizeof(cliaddr);

connfd=accept(listenfd, (struct sockaddr *) &cliaddr, &clilen);

CSE III Year-II Sem Page 38


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

str_echo(connfd);

close(connfd);

void str_echo(int sockfd)

char line[200];int n;

int i=0,j=0;

if((n=read(sockfd,line,200))==0)

return;

else

printf("%s\n",line);

char temp[strlen(line)];

for(i=strlen(line)-1;i>=0;i--,j++)

temp[j]=line[i];

write(sockfd,temp,strlen(temp));

client.c

#include<stdio.h>

#include<sys/types.h>

#include<sys/socket.h>

#include<netinet/in.h>

CSE III Year-II Sem Page 39


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

#include<strings.h>

#include<stdlib.h>

#include<string.h>

#include<time.h>

void str_cli(int);

int main()

int sockfd,n;

char recvline[200];

char str[200];

struct sockaddr_in servaddr;

if((sockfd=socket(AF_INET, SOCK_STREAM,0))<0)

perror("Socket Error");

bzero(&servaddr, sizeof(servaddr));

servaddr.sin_family=AF_INET;

servaddr.sin_port=htons(9000);

if(inet_pton(AF_INET,"127.0.0.1",&servaddr.sin_addr.s_addr)<=0)

perror("Inet pton() Error");

if(connect(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr))<0)

perror("Connect Error");

exit(0);

str_cli(sockfd);

exit(0);

CSE III Year-II Sem Page 40


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

void str_cli(int sockfd)

char sendline[200],recvline[200];

printf("Enter the Data to send to Server\n");

fgets(sendline,80,stdin);

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

if(read(sockfd,recvline,80)<0)

printf("Error reading");

else

printf("Data From Server\n");

fputs(recvline,stdout);

printf("\n");

OUTPUT:

administrator@administrator-Veriton-Series:~/cnnplab$ cc cons.c -o c1

administrator@administrator-Veriton-Series:~/cnnplab$ ./c1

Enter the Data to send to Server

welcome to semaphores

Data From Server

serohpames ot emoclew##

administrator@administrator-Veriton-Series:~/cnnplab$

Week-5
*AIM: Design TCP concurrent server and client application to reverse the
given input sentence.

DESCRIPTION: Concurrent servers process many requests at a time

CSE III Year-II Sem Page 41


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

Steps are required on server side:

1. Create a socket with the socket() system call.


2. Bind the socket to an address using the bind() system call. For a server socket on
the Internet, an address consists of a port number on the host machine.
3. Listen for connections with the listen() system call.
4. Put the accept() system call and the related code in an infinite loop.
5. After a connection is established, call fork() to create a new process.
6. The child process will close listenfd and call str_echo function, passing the
new socket file descriptor as an argument.
7. The parent process closes connfd. Because all of this code is in an infinite loop, it
will return to the accept statement to wait for the next connection
8. Send and receive data using the read() and write() system calls.

Steps are required on client side:

1. Create a socket with the socket() system call.


2. Connect the socket to the address of the server using the connect() system call.
3. Send and receive data. There are a number of ways to do this, but the simplest is
to use the read() and write() system calls.

PROGRAM:
server.c

#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<strings.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>

void str_echo(int);

int main()
{

CSE III Year-II Sem Page 42


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

int listenfd, connfd,n,clilen;


struct sockaddr_in servaddr,cliaddr; char
buff[300];
listenfd =socket(AF_INET, SOCK_STREAM,0);

bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=inet_addr("127.0.0.1");
servaddr.sin_port=htons(19990);

bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr));

listen(listenfd,10);

for(;;){
clilen=sizeof(cliaddr);
connfd=accept(listenfd, (struct sockaddr *) &cliaddr, &clilen);
if(fork()==0)
{
close(listenfd);
str_echo(connfd); exit(0);
}
close(connfd);
}
}
void str_echo(int sockfd)
{
char line[200]; int
i=0,j=0,n;
if((n=read(sockfd,line,200))==0) return;
else
{
printf("%s\n",line);
char temp[strlen(line)];
for(i=strlen(line)-1;i>=0;i--,j++)
{
temp[j]=line[i];

}
write(sockfd,temp,strlen(temp));
}
}

client.c

void str_cli(int);
CSE III Year-II Sem Page 43
COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

int main()
{
int sockfd,n;
char recvline[200], str[200];
struct sockaddr_in servaddr;

if((sockfd=socket(AF_INET,
SOCK_STREAM,0))<0) perror("Socket
Error");

bzero(&servaddr, sizeof(servaddr));

servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(19990);

if(inet_pton(AF_INET,"127.0.0.1",&servaddr.sin_addr.s_addr)<=0)
perror("Inet pton() Error");

if(connect(sockfd,(struct sockaddr
*)&servaddr,sizeof(servaddr))<0){ perror("Connect Error");
exit(0);
}
str_cli(sockfd);
exit(0);

}
void str_cli(int sockfd)
{
char sendline[80],recvline[200];
for(;;)
{
printf("Enter the Data to send to Server\n");
fgets(sendline,80,stdin);
write(sockfd,sendline,strlen(sendline));
if(read(sockfd,recvline,10)==0)
printf("Error reading");
else
{
printf("Data From Server\n");
fputs(recvline,stdout);
printf("\n");
}
}
}

CSE III Year-II Sem Page 44


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

OUTPUT:

Week 6

AIM: Design TCP client and server application to transfer file.

DESCRIPTION:

Steps are required on server side:

1. Create a socket with the socket() system call.


2. Bind the socket to an address using the bind() system call. For a server socket on
the Internet, an address consists of a port number on the host machine.

CSE III Year-II Sem Page 45


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

3. Listen for connections with the listen() system call.


4. Call the accept() statement.
5. After a connection is established, call str_file(), passing the accept system call
descriptor as an argument.
6. In str_file function

a) Read the client request by read() system call, it will return name of the
file
b) Open the client specified file in read mode with the help of fopen().
c) By using while loop read the contents from the file specified by the client
and print them onto network with help of write() system call.

7. Send and receive data using the read() and write() system calls.

Steps are required on client side:

1. Create a socket with the socket() system call.


2. Connect the socket to the address of the server using the connect() system call.
3. Read the name of the file from the standard input device and send it to the
server with the help of write() system call.
4. Read the data which is sent by the server and print that information on standard
output device.

CSE III Year-II Sem Page 46


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

Program:

//server

#include<stdio.h>

#include<sys/types.h>

#include<sys/socket.h>

#include<netinet/in.h>

#include<strings.h>

#include<stdlib.h>

#include<string.h>

#include<time.h>

void str_file(int);

int main()

int listenfd, connfd,n,clilen;

struct sockaddr_in servaddr,cliaddr;

char buff[300];

listenfd =socket(AF_INET, SOCK_STREAM,0);

bzero(&servaddr, sizeof(servaddr));

servaddr.sin_family=AF_INET;

servaddr.sin_addr.s_addr=inet_addr("127.0.0.1");

servaddr.sin_port=htons(5300);

bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr));

listen(listenfd,10);

clilen=sizeof(cliaddr);

connfd=accept(listenfd, (struct sockaddr *) &cliaddr, &clilen);

str_file(connfd);

CSE III Year-II Sem Page 47


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

close(connfd);

void str_file(int sockfd)

FILE *fp;

char s[80],f[80];

printf("client connected");

read(sockfd,f,80);

fp=fopen(f,"r");

printf("%s",f);

while(fgets(s,80,fp)!=NULL)

write(sockfd,s,strlen(s));

//client

#include<stdio.h>

#include<sys/types.h>

#include<sys/socket.h>

#include<netinet/in.h>

#include<strings.h>

#include<stdlib.h>

#include<string.h>

#include<time.h>

void str_cli(int);

int main()

CSE III Year-II Sem Page 48


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

int sockfd,n;

char recvline[200];

char str[200];

struct sockaddr_in servaddr;

if((sockfd=socket(AF_INET, SOCK_STREAM,0))<0)

perror("Socket Error");

bzero(&servaddr, sizeof(servaddr));

servaddr.sin_family=AF_INET;

servaddr.sin_port=htons(5300);

if(inet_pton(AF_INET,"127.0.0.1",&servaddr.sin_addr.s_addr)<=0)

perror("Inet pton() Error");

if(connect(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr))<0){

perror("Connect Error");

exit(0);

str_cli(sockfd);

exit(0);

void str_cli(int sockfd)

char recvline[80],filename[80];

printf("Enter File Name:\n");

scanf("%s",filename);

write(sockfd,filename,sizeof(filename));

printf("Data From Server\n");

CSE III Year-II Sem Page 49


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

while(read(sockfd,recvline,50)!=0){

fputs(recvline,stdout);

file f:

administrator@administrator-Veriton-Series:~/cnnplab$ cat f

hi this is a np lab ..welcomes u..

OUTPUT:

//SERVER

administrator@administrator-Veriton-Series:~/cnnplab$ ./t1

client connected f

administrator@administrator-Veriton-Series:~/cnnplab$ ^C

administrator@administrator-Veriton-Series:~/cnnplab$

//CLIENT

administrator@administrator-Veriton-Series:~/cnnplab$ cc week77.c -o t2

administrator@administrator-Veriton-Series:~/cnnplab$ ./t2

Enter File Name:

Data From Server

hi this is a np lab ..welcomes u..

n}administrator@administrator-Veriton-Series:~/cnnplab$

CSE III Year-II Sem Page 50


COMPUTER NETWORKS & NETWORK PROGRAMMING
LAB

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
only when one or more of these events occurs or when a specified amount of
time has passed.

Prototype:
#include
<sys/select.h>
#include
<sys/time.h>

int select(int maxfdp1, fd_set * readset, fd_set * writeset,


fd_set * exceptset, const struct timeval* timeout ) ;

It takes these parameters:

int maxfdp1 - The highest file descriptor in all given sets plus one
fd_set *readset - File descriptors that will trigger a return when data is
ready to be read
fd_set *writeset - File descriptors that will trigger a return when data is
ready to be written to
fd_set *exceptset - File descriptors that will trigger a return when an
exception occurs
struct timeval *timeout - The maximum period select() should wait for an
event

The time structures involved are defined in <sys/time.h> and look like

struct timeval {
long tv_sec; /* seconds */
long tv_usec; /* microseconds */
};

Macro functions in select:

CSE III Year-II Sem Page 51


COMPUTER NETWORKS & NETWORK PROGRAMMING
LAB

void FD_CLR(int fd, fd_set *set); - Removes the associated fd


from the set int FD_ISSET(int fd, fd_set *set); - Returns a nonzero
value if the fd is in set void FD_SET(int fd, fd_set *set); - Adds the
associated fd to the set

void FD_ZERO(fd_set *set); - Initializes an set to be empty

Returns: positive count of ready descriptors, 0 on timeout, 1 on error. The most


commonly used function for I/O multiplexing is select.

We tell the select function what descriptors we are interested in (for reading,
writing, and exceptions), the maximum amount of time to wait, and the maximum
descriptor number (plus one). Most calls to select specify readability, and we
noted that the only exception condition when dealing with sockets is the arrival of
out-of-band data. Since select provides a time limit on how long a function
blocks, we will use this feature to place a time limit on an input operation.

PROGRAM:

Server.c

#include
<stdio.h>
#include
<sys/types.h>
#include
<sys/socket.h>
#include<stdlib.
h> #include
<netinet/in.h>
#include<strings
.h>
#include<string.
h>
#include<sys/sel
ect.h>
#include<sys/ti
me.h>

#define
MAXLINE
10 main()
{
int
i,j,maxi,maxfd,listenfd,connfd,soc

CSE III Year-II Sem Page 52


COMPUTER NETWORKS & NETWORK PROGRAMMING
LAB

kfd; int
nready,client[FD_SETSIZE];
ssize_t n;
fd_set rset,allset;
char
line[MAXLINE],uline[MAX
LINE]; socklen_t clilen;
struct sockaddr_in cliaddr,servaddr;
puts("socket is creating");
listenfd=socket(AF_INET,SOCK_STRE
AM,0);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=htonl(INADDR
_ANY); servaddr.sin_port=htons(13330);
puts("socket is binding");
bind(listenfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
puts("socket is listening");
listen(listenfd,1024);
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);
puts("connection was established");
for(i=0;i<FD_SETSIZE;i++)
if(client[i]<0)
{
client[i]=connfd;
break;
}
if(i==FD_SETSIZE) puts("too
many clients");
FD_SET(connfd,&allset);
if(connfd>maxfd)

CSE III Year-II Sem Page 53


COMPUTER NETWORKS & NETWORK PROGRAMMING
LAB

maxfd=connfd;
if(i>maxi)
maxi=i; if(--
nready<=0)
continue;
}
for(i=0;i<=maxi;i++)
{
if((sockfd=client[i])<0)
continue;
if(FD_ISSET(sockfd,&rset))
{
puts("\n waiting for reading.......\n");
if(n=read(sockfd,line,MAXLINE)==0)
{
close(connfd);
FD_CLR(sockf
d,&allset);
client[i]=-1;
}
else
for(i=0,j=0;i<strlen(line
);i++,j++)
{
if(line[i]>=97&&line[
j]<=122)
uline[j]=line[i
]-32;
else
uline[j]=line[i];
}
uline[j]=EOF;
uline[++j]="\0";
write(sockfd,uline,strlen(uline));
}
}
}
}

Client.c

void
str_cli(int);
#define

CSE III Year-II Sem Page 54


COMPUTER NETWORKS & NETWORK PROGRAMMING
LAB

MAXLINE
10 int main()
{
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=htons(13330);
servaddr.sin_addr.s_addr=inet_addr("127.0.
0.1");

printf("\n waiting for connection......");

connect(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr));

printf("\nconnection was
established"); str_cli(sockfd);
exit(0);
}
void str_cli(int sockfd)
{
char
sendline[MAXLINE],recvline[MAXLINE];
int maxfdp1;
fd_set rset;
FD_ZERO(&rset
); for(;;)
{
FD_SET(fileno(stdin),&rset
); FD_SET(sockfd,&rset);
maxfdp1=sockfd+1;

select(maxfdp1,&rset,NULL,NULL,NULL);

if(FD_ISSET(sockfd,&rset)){ //socket is
readable
if(read(sockfd,recvline,MAXLINE)==0)
perror("Server terminated permanately");
fputs(recvline,stdout);
}
if(FD_ISSET(fileno(stdin),&rset)){ //input is readable
if(fgets(sendline,MAXLINE,stdin)==NULL)
return; //all done
write(sockfd,sendline,strlen(sendline));

CSE III Year-II Sem Page 55


COMPUTER NETWORKS & NETWORK PROGRAMMING
LAB

}
}

CSE III Year-II Sem Page 56


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

OUTPUT:

CSE III Year-II Sem Page 57


COMPUTER NETWORKS & NETWORK PROGRAMMING
LAB

Week 8

AIM: Design a TCP concurrent server to echo given set of sentences using
poll functions.

DESCRIPTION:

poll() - multiplex input and output

Prototype:
#include <poll.h>
int poll(struct pollfd fds[], nfds_t nfds, int timeout);

The poll() function provides applications with a mechanism for


multiplexing input and output over a set of file descriptors. For each member of
the specified array, poll() examines the given file descriptor for the events
specified in the events member. The poll() function identifies those file
descriptors on which an application can read or write data, or on which certain
events have occurred.

The fds array specified the file descriptors to be examined and the events
of interest for each file descriptor. It is a pointer to an array with one member for
each open file descriptor of interest. The array's members are pollfd structures
within which the fd member specifies an open file descriptor, and the events and
revents members are bitmasks constructed by ORing a combination of the
following event flags:

POLLIN - Data other than high-priority data may be read without


blocking.

POLLRDNORM - Normal data (priority band equals 0) may be read


without blocking.

POLLRDBAND - Data from a non-zero priority band may be read


without blocking.

POLLPRI - High-priority data may be received without blocking.

POLLOUT - Normal data (priority band equals 0) may be written without


blocking

POLLWRNORM - Same as POLLOUT.

POLLWRBAND - Priority data (priority band greater than 0) may be

CSE III Year-II Sem Page 58


COMPUTER NETWORKS & NETWORK PROGRAMMING
LAB

written.

POLLERR - An error has occurred on the device. This flag is only valid
in the revents bitmask; it is ignored in the events member.

POLLHUP - The device has been disconnected. This event and


POLLOUT are mutually exclusive a device can never be writable once a
hangup has occurred. However, this event and POLLIN, POLLRDNORM,
POLLRDBAND, or POLLPRI are not mutually exclusive. This flag is
only valid in the revents bitmask; it is ignored in the events member.

Parameters:

fds - Is an array describing the file descriptors and I/O operations to


return status on. The revents member of each entry is updated on
successful return.

nfds - Is the number of entries in fds.

timeout - Is the minimum number of milliseconds to wait for results. If


this is 0, the call returns immediately. If it is -1, the call blocks
indefinitely, returning only after results are available or the call is
interrupted.

Program

Server.c

#include
<stdio.h>
#include
<sys/types.h>
#include
<sys/socket.h>
#include<stdlib.
h> #include
<netinet/in.h>
#include<strings
.h>
#include<string.
h>
#include<errno.

CSE III Year-II Sem Page 59


COMPUTER NETWORKS & NETWORK PROGRAMMING
LAB

h>
#include<sys/ti
me.h>
#include<limits.
h>
#include<sys/po
ll.h>

#define
OPEN_MAX
10 #define
MAXLINE 10
int main()
{
int
i,maxi,listenfd,connfd,soc
kfd; int nready;
ssize_t n;
char
buf[MAXLIN
E]; socklen_t
clilen; struct
pollfd
client[32];
struct sockaddr_in cliaddr,servaddr;

printf("\n socket creating..");


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

printf("\n binding the server socket");


bind(listenfd,(struct sockaddr *)&servaddr,sizeof(servaddr));

printf("\n socket is listening");


listen(listenfd,1024);
client[0].fd=listenfd;
client[0].events=POLLIN;
for(i=1;i<32;i++)
client[i].fd=-
1; maxi=0;
for(;;)
{

CSE III Year-II Sem Page 60


COMPUTER NETWORKS & NETWORK PROGRAMMING
LAB

nready=poll(client,maxi+1,200);
if(client[0].revents & POLLIN)
{
clilen=sizeof(cliaddr);
connfd=accept(listenfd,(struct sockaddr
*)&cliaddr,&clilen);
printf("\n connection is established");
for(i=1;i<32;i++)
if(client[i].fd<0)
{
client[i].fd=connfd;
break;
}
if(i==32)
printf("too many clients");
client[i].events=POLLIN;
if(i>maxi)
maxi=i;
if(--nready<=0)
continue;
}
for(i=1;i<=maxi;i++)
{
if((sockfd=client[i].fd)<0)
continue;
if(client[i].revents&
POLLIN)
{
if((n=read(sockfd,buf,MAXLINE))<0)
{
if(errno==ECONNRESET)
{
close(
sockfd
);
client[
i].fd=-
1;
}
else
printf("read error");
}
else if(n==0)
{
close(

CSE III Year-II Sem Page 61


COMPUTER NETWORKS & NETWORK PROGRAMMING
LAB

sockfd
);
client[
i].fd=-
1;
}
else{
printf("%s",buf);
write(sockfd,
buf,n);} if(--
nready<=0)
break;
}
}
}
}

Client.c

#include<poll.h>
#include<sys/stropts.h>
void str_cli(FILE
*fp,int sockfd); #define
MAXLINE 10
int main()
{
int sockfd;
struct sockaddr_in servaddr;
sockfd=socket(AF_INET,SOCK_S
TREAM,0);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(20012);

inet_pton(AF_INET,"127.0.0.1",&servaddr.sin_addr
); printf("\n waiting for connection...");
connect(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
printf("\n connection was established");
str_cli(stdin,sockfd);
exit(0);
}
void str_cli(FILE *fp,int sockfd)
{
char
sendline[MAXLINE],reculine[MAXLINE];
CSE III Year-II Sem Page 62
COMPUTER NETWORKS & NETWORK PROGRAMMING
LAB

printf("\n enter text");


while(fgets(sendline,MAXLINE,fp)!=NULL)
{
write(sockfd,sendline,strlen(sendline));
if(read(sockfd,reculine,MAXLINE)==0)
printf("\n str_cli=server terminated permanently");
fputs(reculine,stdout);
printf("\n enter text");
}
}

CSE III Year-II Sem Page 63


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

OUTPUT:

CSE III Year-II Sem Page 64


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

Week 9

AIM: Design UDP Client and server application to reverse the given input sentence.

DESCRIPTION:

Steps are required on server side:

1. Create a socket with the socket() system call.


2. Bind the socket to an address using the bind() system call. For a server socket on
the Internet, an address consists of a port number on the host machine.
3. Accept a request and data from the network with the recvfrom() system call. This
call typically blocks until a client connects with the server.
4. Send the data using sendto() system call.

Steps are required on client side:


CSE III Year-II Sem Page 65
COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

1. Create a socket with the socket() system call.


2. Send the data to the server by specifying port and address of the server as an
arguments to the connect() system call.
3. Receive the data from the network using recvfrom() system call.

System calls

recvfrom() - receive a message from a socket

Prototype:

#include <sys/socket.h>

ssize_t recvfrom(int socket, void *buffer, size_t length, int flags,


struct sockaddr *address, socklen_t *address_len);

DESCRIPTION

The recvfrom() function receives a message from a connection-mode or


connectionless-mode socket. It is normally used with connectionless-mode sockets
because it permits the application to retrieve the source address of received data.

The function takes the following arguments:

socket - Specifies the socket file descriptor.

Buffer - Points to the buffer where the message should be stored.

length - Specifies the length in bytes of the buffer pointed to by the buffer
argument.

Address - A null pointer, or points to a sockaddr structure in which the sending


address is to be stored. The length and format of the address depend on the
address family of the socket.

address_len - Specifies the length of the sockaddr structure pointed to by the


address argument.

sendto() - send a message on a socket


Prototype:

CSE III Year-II Sem Page 66


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

#include <sys/socket.h>

ssize_t sendto(int socket, const void *message, size_t length, int flags,
const struct sockaddr *dest_addr, socklen_t dest_len);

DESCRIPTION:
The sendto() function sends a message through a connection-mode or connectionless-
mode socket. If the socket is connectionless-mode, the message will be sent to the
address specified by dest_addr. If the socket is connection-mode, dest_addr is ignored.

The function takes the following arguments:

socket - Specifies the socket file descriptor.

message - Points to a buffer containing the message to be sent.

length - Specifies the size of the message in bytes.

flags- Specifies the type of message transmission. Values of this argument are
formed by logically OR'ing zero or more of the following flags:

MSG_EOR - Terminates a record (if supported by the protocol)

MSG_OOB - Sends out-of-band data on sockets that support out-of-band


data. The significance and semantics of out-of-band data are protocol-
specific.

dest_addr - Points to a sockaddr structure containing the destination address. The


length and format of the address depend on the address family of the socket.

dest_len - Specifies the length of the sockaddr structure pointed to by the


dest_addr argument.

Program:

server.c

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include<stdlib.h> #include
<netinet/in.h>
#include<strings.h>
#include<string.h> #define
MAXLINE 10

CSE III Year-II Sem Page 67


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

int main()
{
int sockfd;
struct sockaddr_in servaddr, cliaddr; 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(9999);

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

dg_echo(sockfd, (struct sockaddr *) &cliaddr, sizeof(cliaddr));


}
void dg_echo(int sockfd, struct sockaddr *pcliaddr, socklen_t clilen)
{
int i,j,n; socklen_t
len;
char mesg[MAXLINE];

for ( ; ; ) {
len = clilen;
n = recvfrom(sockfd, mesg, MAXLINE, 0, pcliaddr, &len);
char temp[strlen(mesg)]; for(i=strlen(mesg)-1,j=0;i>=0;i--,j++)
{
temp[j]=mesg[i];
}
sendto(sockfd, temp, n, 0, pcliaddr, len);
}
}
client.c

#define MAXLINE
10 int main()
{
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(9999);
servaddr.sin_addr.s_addr=inet_addr("127.0.0.1");
dg_cli(stdin, sockfd, (struct sockaddr *) &servaddr,
sizeof(servaddr)); exit(0);

CSE III Year-II Sem Page 68


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

void dg_cli(FILE *fp, int sockfd, const struct sockaddr *pservaddr,


socklen_t servlen)
{
int n;
char sendline[MAXLINE], recvline[MAXLINE + 1];

if (fgets(sendline, MAXLINE, fp) != NULL) {


sendto(sockfd, sendline, strlen(sendline), 0, pservaddr, servlen);
n = recvfrom(sockfd, recvline, MAXLINE, 0, NULL, NULL);
recvline[n] = 0; /* null terminate */
fputs(recvline, stdout);
}
}

CSE III Year-II Sem Page 69


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

OUTPUT:

CSE III Year-II Sem Page 70


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

Week 10

AIM: Design UDP Client server to transfer a file.

DESCRIPTION:

Steps are required on server side:

1. Create a socket with the socket() system call.


2. Bind the socket to an address using the bind() system call. For a server socket on
the Internet, an address consists of a port number on the host machine.
3. After bind(), call dg_echo().
4. Accept a request and data from the network with the recvfrom() system call. This
call typically blocks until a client connects with the server.
5. In dg_echo()function
1. Open the client specified file in read mode with the help of fopen().
2. By using while loop read the contents from the file specified by the client
and print them onto network with help of sendto() system call.

Steps are required on client side:

1. Create a socket with the socket() system call.


2. Send the name of the file to the server by specifying port and address of the
server as an arguments to the connect() system call.
3. Receive the data from the network using recvfrom() system call and print the
data on the console.

Program:

server.c

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include<stdlib.h>
#include <netinet/in.h>

CSE III Year-II Sem Page 71


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

#include<strings.h>
#include<string.h>

#define MAXLINE 10

int main()
{
int sockfd;
struct sockaddr_in servaddr, cliaddr; sockfd =
socket(AF_INET, SOCK_DGRAM, 0);

bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family =


AF_INET; servaddr.sin_addr.s_addr =
inet_addr("127.0.0.1"); servaddr.sin_port = htons(15123);

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

dg_echo(sockfd, (struct sockaddr *) &cliaddr, sizeof(cliaddr));


}
void dg_echo(int sockfd, struct sockaddr *pcliaddr, socklen_t clilen)
{
int len,n,i=0;
char send[80],mesg[80],temp[20]; len =
clilen;
n=recvfrom(sockfd,mesg,20,0,pcliaddr,&len);
for(i=0;i<n;i++)
if(mesg[i]!='.')
temp[i]=mesg[i];
else
{
temp[i]='\0';
break;
}
strcat(temp,".c");

fp=fopen(temp,"r");

while(fgets(send,80,fp)!=NULL)
{
printf("%s",send);
sendto(sockfd, send, 80, 0, pcliaddr, len);
}
}

CSE III Year-II Sem Page 72


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

client.c

#define MAXLINE 80

int main()
{
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(15123);
servaddr.sin_addr.s_addr=inet_addr("127.0.0.1");

dg_cli(stdin, sockfd, (struct sockaddr *) &servaddr,


sizeof(servaddr)); exit(0);
}

void dg_cli(FILE *fp, int sockfd, const struct sockaddr *pservaddr,


socklen_t servlen)
{
int n;
char sendline[MAXLINE], recvline[MAXLINE + 1];
connect(sockfd,(struct sockaddr *)pservaddr,servlen); if
(fgets(sendline, MAXLINE, fp) != NULL)
{
write(sockfd, sendline, 80);
for(;;){
n = read(sockfd, recvline, MAXLINE);
recvline[n] = 0; /* null terminate */
fputs(recvline, stdout);
}
}
}

CSE III Year-II Sem Page 73


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

OUTPUT:

CSE III Year-II Sem Page 74


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

Week 11
AIM: Design using poll client server application to multiplex TCP and UDP requests for
converting a given text into upper case.
DESCRIPTION:
Steps are required on server side:

1. Create a listening TCP socket with the socket() system call and bound to the
servers port.
2. Create a UDP socket with the socket() system call and bound some other port number
to the same address.
3. Use poll() function to multiplex the TCP and UDP clients requests with the help of
POLLIN events.
Program:

server.c

#include<sys/poll.h> #define
MAXLINE 10
void capital(char line[MAXLINE]); int
main()
{
int i,listenfd,connfd,udpfd; const int
on=1;
int nready;
char buf[MAXLINE];
socklen_t clilen; struct pollfd
client[3];

struct sockaddr_in cliaddr,servaddr;

printf("\n TCP socket creating..");


listenfd=socket(AF_INET,SOCK_STREAM,0);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=inet_addr("127.0.0.1");
servaddr.sin_port=htons(20012);

//setsockopt(listenfd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on));

printf("\n TCP binding the server socket"); bind(listenfd,(struct sockaddr

CSE III Year-II Sem Page 75


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

*)&servaddr,sizeof(servaddr));

printf("\n UDP socket creating..");


udpfd=socket(AF_INET,SOCK_DGRAM,0);
bzero(&servaddr,sizeof(servaddr)); servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=inet_addr("127.0.0.1");
servaddr.sin_port=htons(20012);

printf("\n UDP binding the server socket & Waiting for connection with client");
bind(udpfd,(struct sockaddr *)&servaddr,sizeof(servaddr));

printf("\n TCP socket is listening ");


listen(listenfd,1024); client[0].fd=listenfd;
client[0].events=POLLIN; client[1].fd=udpfd;
client[1].events=POLLIN;

for(;;)
{
nready=poll(client,2,200); if(client[0].revents
& POLLIN)
{
clilen=sizeof(cliaddr); connfd=accept(listenfd,(struct
sockaddr
*)&cliaddr,&clilen);
printf("\n TCP connection is established"); int
n=read(connfd,buf,MAXLINE); capital(buf);
write(connfd,buf,n);
}

if(client[1].revents & POLLIN)


{
clilen=sizeof(cliaddr); recvfrom(udpfd,buf,MAXLINE,0,(struct
sockaddr
*)&cliaddr,&clilen);
printf("\n UDP -- Data is Received From Client"); capital(buf);
sendto(udpfd,buf,MAXLINE,0,(struct sockaddr
*)&cliaddr,clilen);

}
}
}
void capital(char buf[MAXLINE])
{
int i; for(i=0;i<strlen(buf);i++)
{
if(buf[i]>=97&&buf[i]<=122)

CSE III Year-II Sem Page 76


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

buf[i]=buf[i]-32;
else
buf[i]=buf[i];
}
buf[i]=EOF;
buf[++i]='\0';
}

Code: TCPClient.c

void str_cli(int); int


main()
{
int sockfd,n;

struct sockaddr_in servaddr;

if((sockfd=socket(AF_INET, SOCK_STREAM,0))<0)
perror("Socket Error");

bzero(&servaddr, sizeof(servaddr));

servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=inet_addr("127.0.0.1");
servaddr.sin_port=htons(20012);

if(connect(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr))<0){


perror("Connect Error");
exit(0);
}
str_cli(sockfd); exit(0);

}
void str_cli(int sockfd)
{
char sendline[200],recvline[200]; printf("Enter the
Data to send to Server\n"); fgets(sendline,80,stdin);
write(sockfd,sendline,strlen(sendline));
if(read(sockfd,recvline,80)<0) printf("Error reading"); else{
printf("Data From Server\n");
fputs(recvline,stdout); printf("\n");
}

CSE III Year-II Sem Page 77


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

Code: UDPClient.c

#define MAXLINE 10 int


main()
{
int sockfd;
struct sockaddr_in servaddr;

bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(20012);
servaddr.sin_addr.s_addr=inet_addr("127.0.0.1"); sockfd
= socket(AF_INET, SOCK_DGRAM, 0);
dg_cli(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr));
exit(0);
}

void dg_cli(int sockfd, const struct sockaddr *pservaddr, socklen_t servlen)


{
int n;
char sendline[MAXLINE], recvline[MAXLINE + 1];

if (fgets(sendline, MAXLINE,stdin) != NULL) {


sendto(sockfd, sendline, strlen(sendline), 0, pservaddr, servlen); n =
recvfrom(sockfd, recvline, MAXLINE, 0, NULL, NULL); recvline[n] =
0; /* null terminate */
fputs(recvline, stdout);
}
}

CSE III Year-II Sem Page 78


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

OUTPUT:

CSE III Year-II Sem Page 79


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

Week 12

AIM: Design a RPC application to add and subtract a given pair of integers

DESCRIPTION:

Remote Procedure Call (RPC) provides a different paradigm for accessing network
services. Instead of accessing remote services by sending and receiving messages, a client
invokes services by making a local procedure call. The local procedure hides the details of the
network communication.

When making a remote procedure call:

1. The calling environment is suspended, procedure parameters are transferred across the
network to the environment where the procedure is to execute, and the procedure is
executed there.
2. When the procedure finishes and produces its results, its results are transferred back to
the calling environment, where execution resumes as if returning from a regular
procedure call.

The main goal of RPC is to hide the existence of the network from a program. As a result,
RPC doesn't quite fit into the OSI model:

1. The message-passing nature of network communication is hidden from the user. The user
doesn't first open a connection, read and write data, and then close the connection.
Indeed, a client often doesn not even know they are using the network!
2. RPC often omits many of the protocol layers to improve performance. Even a small
performance improvement is important because a program may invoke RPCs often.
For example, on (diskless) Sun workstations, every file access is made via an RPC.

RPC is especially well suited for client-server (e.g., query-response) interaction in which the
flow of control alternates between the caller and callee.

Program Implementations:

Code: rpcaddsub.x

struct values
{
int a; int b;
};
typedef struct values val; program
RPCADDSUB
{
version RPCADDSUBVERSION

CSE III Year-II Sem Page 80


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

{
int ADD(val)=1; int
SUB(val)=2; }=1;
}=2000009;

Code : rpcaddsub_client.c

#include "rpcaddsub.h"
void rpcaddsub_1(char *host)
{
CLIENT *clnt; int
*result_1; int
*result_2;
struct values *ar=(struct values *)malloc(sizeof(struct values));
printf("Enter Number");
scanf("%d",&ar->a); printf("enter
second number"); scanf("%d",&ar-
>b);
clnt=clnt_create(host,RPCADDSUB,RPCADDSUBVERSION,"udp");
if(clnt==NULL)
{
clnt_pcreateerror(host); exit(1);
}
result_1=add_1(ar,clnt);
result_2=sub_1(ar,clnt);
if(result_1==(int *)NULL)
{
clnt_perror(clnt,"client failed");
}
else
{
printf("Addition Result:%d",*result_1);
printf("\nSubtraction result:%d",*result_2);
clnt_destroy(clnt);
}
}
int main(int argc,char *argv[])
{

char *host;
if(argc>2)
{
printf("Usage:%s Serverhost\n",argv[0]);
exit(1);
}

CSE III Year-II Sem Page 81


COMPUTER NETWORKS & NETWORK PROGRAMMING LAB

host=argv[1];
rpcaddsub_1(host); exit(0);
}
Code: rpcaddsub_server.c
#include "rpcaddsub.h"
int* add_1_svc(struct values *argp,struct svc_req *rqstp)
{
static int res; res=argp-
>a+argp->b; return &res;
}
int* sub_1_svc(struct values *argp,struct svc_req *rqstp)
{
static int res1; res1=argp->a-
argp->b; return &res1;
}

Execution and OUTPUT:


Generation of Client Server stubs:
$ rpcgen rpcaddsub.x

Linking and execution of RPC Server:

$ gcc -c rpcaddsub_server.c -o rpcaddsub_server.o


$ gcc -o rpcaddsubserver rpcaddsub_server.o rpcaddsub_svc.c rpcaddsub_xdr.c

Linking and execution of RPC Client:


$ cc -c rpcaddsub_client.c -o rpaddsub_client.o
$ cc -o rpcaddsubclient rpaddsub_client.o rpcaddsub_clnt.c rpcaddsub_xdr.c $
./rpcaddsubserver & 19692
$ ./rpcaddsubclient 127.0.0.1

Enter Number12
enter second number23 Addition
Result:35 Subtraction result:-11

CSE III Year-II Sem Page 82

Вам также может понравиться