Documente Academic
Documente Profesional
Documente Cultură
PRACTICAL RECORD
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
3. Write a programme to create an integer variable using shared memory concept and
increment the variable
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
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
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
PART :A
Week1
Implementation of the data link layer framing methods such as bit stuffing and
character 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$
#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];
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
OUTPUT:
Quotient is1100001010
Remainder is1110
Final data is11010110111110guest-30708q@administrator-W52K55:~/cnnplab$ BB^C
guest-30708q@administrator-W52K55:~/cnnplab$
Week3
Implementation of dijkstras algorithm to compute the shortest path thru a graph.
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#define infinity 999
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
shortest path:
1->4,cost=2
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;
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
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;
}
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
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.
Using pipes
Prototype:
#include <unistd.h>
int pipe( int fd[2] );
Returns: 0 on success
-1 on error
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).
Prototype:
#include <unistd.h>
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
#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).
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>
#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())
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
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>
main()
char s[300];
int num,fd;
switch(fork())
exit(1);
while(scanf("%s",s),!feof(stdin))
if((num=write(fd,s,strlen(s)))==-1)
perror("Error\n");
else
break;
default:
fd=open(FIFO_NAME, O_RDONLY);
do
if((num=read(fd,s,300))==-1)
perror("Error\n");
else
s[num]='\0';
}while(num>0);
break;
OUTPUT:
administrator@administrator-Veriton-Series:~/cnnplab$ cc fifo1.c
administrator@administrator-Veriton-Series:~/cnnplab$ ./a.out
Get a Writer :3
hi
welcome
^C
administrator@administrator-Veriton-Series:~/cnnplab$
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>
#include<sys/msg.h>
int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);
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.
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.
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.
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;
printf("%d",q_id);
while(1)
rc=msgrcv(q_id,rcv,80,0,MSG_NOERROR);
if(rc<1)
perror("Main: msgrcv\n");
exit(1);
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;
char mtext[1];
};
main()
char s[80];
FILE *fp;
fp=fopen("pipe1.c","r");
if(q_id==-1)
perror("msgget(): Error\n");
exit(1);
while(fgets(s,80,fp)!=NULL)
msg->mtype=1;
strcpy(msg->mtext,s);
msgsnd(q_id,msg,strlen(s),0);
sleep(2);
OUTPUT:
administrator@administrator-Veriton-Series:~/cnnplab$ cc process2.c -o s1
administrator@administrator-Veriton-Series:~/cnnplab$ ./s1
process2:
administrator@administrator-Veriton-Series:~/cnnplab$ cc process1.c -o s2
administrator@administrator-Veriton-Series:~/cnnplab$ ./s2
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.
IMPLEMENTATION:
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.
Upon creation, the least significant 9 bits of the argument semflg define the
permissions (for owner, group and others) for the semaphore set.
Prototype:
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:
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:
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:
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.
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.
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);
int* cnt=0;
main()
int shmid;
char* shm_addr;
int i;
shmid=shmget(1,getpagesize(),IPC_CREAT | 0644);
shm_addr=shmat(shmid, 0,SHM_RND);
cnt=(int *)shm_addr;
sem_set_id=semget(SEM_ID,1,IPC_CREAT | 0600);
semctl(sem_set_id,0,SETVAL,1);
switch(fork())
exit(2);
case 0:
i=0;
while(i<10)
sleep(1);
printf("Child:");
executeProcess(sem_set_id);
i++;
break;
default:
i=0;
while(i<10)
sleep(1);
printf("Parent :");
executeProcess(sem_set_id);
i++;
break;
sem_op.sem_num=0;
sem_op.sem_op=-1;
sem_op.sem_flg=0;
semop(sem_set_id,&sem_op,1);
printf("%d\n",(*cnt)++);
sem_op.sem_num=0;
sem_op.sem_op=1;
sem_op.sem_flg=0;
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
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.
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
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.
Prototype:
#include <sys/socket.h>
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.
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
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>
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:
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.
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()
char buff[300];
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);
listen(listenfd,10);
for(;;)
clilen=sizeof(cliaddr);
str_echo(connfd);
close(connfd);
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>
#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];
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("Connect Error");
exit(0);
str_cli(sockfd);
exit(0);
char sendline[200],recvline[200];
fgets(sendline,80,stdin);
write(sockfd,sendline,strlen(sendline));
if(read(sockfd,recvline,80)<0)
printf("Error reading");
else
fputs(recvline,stdout);
printf("\n");
OUTPUT:
administrator@administrator-Veriton-Series:~/cnnplab$ cc cons.c -o c1
administrator@administrator-Veriton-Series:~/cnnplab$ ./c1
welcome to semaphores
serohpames ot emoclew##
administrator@administrator-Veriton-Series:~/cnnplab$
Week-5
*AIM: Design TCP concurrent server and client application to reverse the
given input sentence.
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()
{
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);
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");
}
}
}
OUTPUT:
Week 6
DESCRIPTION:
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.
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()
char buff[300];
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);
listen(listenfd,10);
clilen=sizeof(cliaddr);
str_file(connfd);
close(connfd);
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()
int sockfd,n;
char recvline[200];
char str[200];
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("Connect Error");
exit(0);
str_cli(sockfd);
exit(0);
char recvline[80],filename[80];
scanf("%s",filename);
write(sockfd,filename,sizeof(filename));
while(read(sockfd,recvline,50)!=0){
fputs(recvline,stdout);
file f:
administrator@administrator-Veriton-Series:~/cnnplab$ cat f
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
n}administrator@administrator-Veriton-Series:~/cnnplab$
Week 7
Prototype:
#include
<sys/select.h>
#include
<sys/time.h>
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 */
};
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
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)
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
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("\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));
}
}
OUTPUT:
Week 8
AIM: Design a TCP concurrent server to echo given set of sentences using
poll functions.
DESCRIPTION:
Prototype:
#include <poll.h>
int poll(struct pollfd fds[], nfds_t nfds, int timeout);
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:
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.
Parameters:
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.
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;
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(
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
OUTPUT:
Week 9
AIM: Design UDP Client and server application to reverse the given input sentence.
DESCRIPTION:
System calls
Prototype:
#include <sys/socket.h>
DESCRIPTION
length - Specifies the length in bytes of the buffer pointed to by the buffer
argument.
#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.
flags- Specifies the type of message transmission. Values of this argument are
formed by logically OR'ing zero or more of the following flags:
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
int main()
{
int sockfd;
struct sockaddr_in servaddr, cliaddr; sockfd =
socket(AF_INET, SOCK_DGRAM, 0);
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);
OUTPUT:
Week 10
DESCRIPTION:
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
int main()
{
int sockfd;
struct sockaddr_in servaddr, cliaddr; sockfd =
socket(AF_INET, SOCK_DGRAM, 0);
fp=fopen(temp,"r");
while(fgets(send,80,fp)!=NULL)
{
printf("%s",send);
sendto(sockfd, send, 80, 0, pcliaddr, len);
}
}
client.c
#define MAXLINE 80
int main()
{
int sockfd;
struct sockaddr_in servaddr;
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");
OUTPUT:
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];
//setsockopt(listenfd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on));
*)&servaddr,sizeof(servaddr));
printf("\n UDP binding the server socket & Waiting for connection with client");
bind(udpfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
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);
}
}
}
}
void capital(char buf[MAXLINE])
{
int i; for(i=0;i<strlen(buf);i++)
{
if(buf[i]>=97&&buf[i]<=122)
buf[i]=buf[i]-32;
else
buf[i]=buf[i];
}
buf[i]=EOF;
buf[++i]='\0';
}
Code: TCPClient.c
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);
}
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");
}
Code: UDPClient.c
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);
}
OUTPUT:
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.
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
{
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);
}
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;
}
Enter Number12
enter second number23 Addition
Result:35 Subtraction result:-11