Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 40

JAWAHARLA NEHRU TECHNOLOGICAL UNIVERSITY KAKINADA

UNIVERSITY COLLEGE OF ENGINEERING VIZIANAGARAM

NETWORK PROGRAMMING LAB

REG NO:18
Certificate
Certified that this is a bonafide record of practical work done by
Mr./ Kumari ______________________________________
of _______________ class in ______________________
laboratories of ______________________ college during the year
____________

No. of expts. done and certified:

Lecture-in-charge Head
of the department
Date:

INDEX
SN DATE NAME OF THE EXPERIMENT PAGE NO MARKS REMARK
O AWARDE S
D

week-1
Aim: write a c program for bit stuffing.
Description:-Bit stuffing is the process of inserting noninformation bits into data to break up bit
patterns to affect the synchronous transmission of information. It is widely used in network and
communication protocols, in which bit stuffing is a required part of the transmission process. Bit
stuffing is commonly used to bring bit streams up to a common transmission rate or to fill frames.
Bit stuffing is also used for run-length limited coding.
Example of bit stuffing –
Bit sequence: 110101111101011111101011111110 (without bit stuffing)
Bit sequence: 110101111100101111101010111110110 (with bit stuffing)
After 5 consecutive 1-bits, a 0-bit is stuffed. Stuffed bits are marked bold.

Program:-
#include<stdio.h>
#include<string.h>
int main()
{
int a[20],b[30],i,j,k,count,n;
printf("Enter frame size (Example: 8):");
scanf("%d",&n);
printf("Enter the frame in the form of 0 and 1 :");
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 Bit Stuffing :");
for(i=0; i<j; i++)
printf("%d",b[i]);
return 0;
}

Output:

WEEK-2
Aim :- write a c program for character stuffing
Description:- Character stuffing a particular byte is added to the data section of the frame when
there is a character with the same pattern as the flag. The data section is stuffed with an extra byte.
This byte is usually known as the escape character (ESC), which has a predefined bit pattern.
Whenever the receiver encounters the ESC character, it deletes it from the data section and treats
the next character as data, not a delimiting flag.

Program:-
#include<stdio.h>

#include<conio.h>

#include<string.h>

#include<process.h>

char a[20],b[50],c[50],ch;

int i=0,n;

void sender();

void receiver();

void main()

clrscr();

sender();

receiver();

getch();

void sender()

int j=0,pos;

printf("\n\n Sender side \n\n");

printf("Enter string : ");

scanf("%s",&a);

n=strlen(a);

printf("\n Enter position : ");

scanf("%d",&pos);
label: if(pos>n)

printf("\n Invalid position, Enter again : ");

scanf("%d",&pos);

goto label;

printf("\n Enter the character : ");

ch=getche();

b[0]='d';

b[1]='l';

b[2]='e';

b[3]='s';

b[4]='t';

b[5]='x';

j=6;

while(i<n)

if(i==pos-1)

b[j]='d';

b[j+1]='l';

b[j+2]='e';

b[j+3]=ch;

b[j+4]='d';

b[j+5]='l';

b[j+6]='e';
j=j+7;

if(a[i]=='d' && a[i+1]=='l' && a[i+2]=='e')

b[j]='d';

b[j+1]='l';

b[j+2]='e';

j=j+3;

b[j]=a[i];

i++;

j++;

b[j]='d';

b[j+1]='l';

b[j+2]='e';

b[j+3]='e';

b[j+4]='t';

b[j+5]='x';

b[j+6]='\0';

printf("\nframe after stuffing : %s" ,b);

void receiver()

int j=6;

printf("\n\n\n\n Receiver side\n\n");


printf("\nThe data came from sender side is : %s",b);

n=strlen(b);

while(j<n-6)

if(b[j]=='d' && b[j+1]=='l' && b[j+2]=='e')

if(b[j+3]=='d' && b[j+4]=='l' && b[j+5]=='e')

c[i]=b[j+3];

c[i+1]=b[j+4];

c[i+2]=b[j+5];

i = i+3;

j = j+6;

else if(b[j+4]=='d' && b[j+5]=='l' && b[j+6]=='e')

j = j+7;

else

c[i]=b[j];

i++;

j++;

}
printf("\n\nOriginal data : %s",a);

Output:-

WEEK-3

Aim: - Implementation of IPC using pipe


Description: -Pipe is a communication medium between two or more related or interrelated
processes. It can be either within one process or a communication between the child and the parent
processes. Communication can also be multi-level such as communication between the parent, the
child and the grand-child, etc. Communication is achieved by one process writing into the pipe and
other reading from the pipe. To achieve the pipe system call, create two files, one to write into the
file and another to read from the file.

Program: -
#include<stdio.h>
#include<unistd.h>

int main () {
int pipefds[2];
int returnstatus;
char writemessages[2][20]={"Hi", "Hello"};
char readmessage[20];
returnstatus = pipe(pipefds);

if (returnstatus == -1) {
printf("Unable to create pipe\n");
return 1;
}

printf("Writing to pipe - Message 1 is %s\n", writemessages[0]);


write(pipefds[1], writemessages[0], sizeof(writemessages[0]));
read(pipefds[0], readmessage, sizeof(readmessage));
printf("Reading from pipe – Message 1 is %s\n", readmessage);
printf("Writing to pipe - Message 2 is %s\n", writemessages[0]);
write(pipefds[1], writemessages[1], sizeof(writemessages[0]));
read(pipefds[0], readmessage, sizeof(readmessage));
printf("Reading from pipe – Message 2 is %s\n", readmessage);
return 0;
}
output:-

WEEK-4

Aim: - Implementation of IPC using FIFO


Description:-A FIFO (First In First Out) is similar to a pipe. The principal difference is that a FIFO
has a name within the file system and is opened in the same way as a regular file. This allows a
FIFO to be used for communication between unrelated process.

Program:
server side:-
// C program to implement one side of FIFO
// This side writes first, then reads
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
int fd;

// FIFO file path


char * myfifo = "/tmp/myfifo";

// Creating the named file(FIFO)


// mkfifo(<pathname>, <permission>)
mkfifo(myfifo, 0666);

char arr1[80], arr2[80];


while (1)
{
// Open FIFO for write only
fd = open(myfifo, O_WRONLY);

// Take an input arr2ing from user.


// 80 is maximum length
fgets(arr2, 80, stdin);

// Write the input arr2ing on FIFO


// and close it
write(fd, arr2, strlen(arr2)+1);
close(fd);

// Open FIFO for Read only


fd = open(myfifo, O_RDONLY);

// Read from FIFO


read(fd, arr1, sizeof(arr1));

// Print the read message


printf("User2: %s\n", arr1);
close(fd);
}
return 0;
}

client side:-
// C program to implement one side of FIFO
// This side reads first, then reads
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
int fd1;

// FIFO file path


char * myfifo = "/tmp/myfifo";

// Creating the named file(FIFO)


// mkfifo(<pathname>,<permission>)
mkfifo(myfifo, 0666);

char str1[80], str2[80];


while (1)
{
// First open in read only and read
fd1 = open(myfifo,O_RDONLY);
read(fd1, str1, 80);

// Print the read string and close


printf("User1: %s\n", str1);
close(fd1);

// Now open in write mode and write


// string taken from user.
fd1 = open(myfifo,O_WRONLY);
fgets(str2, 80, stdin);
write(fd1, str2, strlen(str2)+1);
close(fd1);
}
return 0;
}

output :-
WEEK-5

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


DESCRIPTION:- A message queue is a linked list of messages stored within the kernel and
identified by a message queue identifier. A new queue is created or an existing queue
opened by msgget(). 
New messages are added to the end of a queue by msgsnd(). Every message has a
positive long integer type field, a non-negative length, and the actual data bytes
(corresponding to the length), all of which are specified to msgsnd() when the message is
added to a queue. Messages are fetched from a queue by msgrcv(). We don’t have to fetch
the messages in a first-in, first-out order. Instead, we can fetch messages based on their
type field.

PROGRAM:-
SENDER SIDE:-

// C Program for Message Queue (Sender process)


#include <stdio.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define MAX 10

// structure for message queue


struct mesg_buffer {
long mesg_type;
char mesg_text[100];
} message;

int main()
{
key_t key;
int msgid;

// ftok to generate unique key


key = ftok("progfile", 65);

msgid = msgget(key, 0666 | IPC_CREAT);


message.mesg_type = 1;

printf("Write Data : ");


fgets(message.mesg_text,MAX,stdin);

// msgsnd to send message


msgsnd(msgid, &message, sizeof(message), 0);

// display the message


printf("Data send is : %s \n", message.mesg_text);

return 0;
}

RECEIVERS SIDE:-
// C Program for Message Queue (Receivers side)
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/msg.h>

// structure for message queue


struct mesg_buffer {
long mesg_type;
char mesg_text[100];
} message;

int main()
{
key_t key;
int msgid;

// ftok to generate unique key


key = ftok("progfile", 65);

// msgget creates a message queue


// and returns identifier
msgid = msgget(key, 0666 | IPC_CREAT);

// msgrcv to receive message


msgrcv(msgid, &message, sizeof(message), 1, 0);

// display the message


printf("Data Received is : %s \n",
message.mesg_text);

// to destroy the message queue


msgctl(msgid, IPC_RMID, NULL);

return 0;
}

OUTPUT:-
Week-6
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 :-
In a multiprogrammed system, there are several processes "active" at once. Even a single job can create multiple processes. Only one
process can be executing at any instant in time given a uni-processor.
Race Conditions A potential IPC problem when two or more processes interact via shared data. Final outcome depends on the exact
instruction sequence of the processes. Instruction-by-instruction sequence determined by the OS CPU Scheduler. Depends on which
process "wins" the "race".
PROGRAM:
#include <unistd.h>
#include <errno.h>
#include <sys/stat.h>
#include <string.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <sys/sem.h>
# include <stdlib.h>

#define SHMSZ 4 /* Good for integer */


#define BUF_SZ 16
#define SHM_KEY 1234
#define SEM_KEY 1235
#define CHILD_INCREMENT_COUNT 67787
#define PARENT_INCREMENT_COUNT 84823

union semun {
int val; /* value for SETVAL */
struct semid_ds *buf; /* buffer for IPC_STAT, IPC_SET */
unsigned short *array; /* array for GETALL, SETALL */
/* Linux specific part: */
struct seminfo *__buf; /* buffer for IPC_INFO */
};

int main()
{
int shmid;
int semid;
key_t key;
int *child_shm, *parent_shm;
union semun arg;
int i;
struct sembuf operations[1];
int status;
int pid;

if ((shmid = shmget(SHM_KEY, SHMSZ, IPC_CREAT | 0666)) < 0) {


perror("shmget");
exit(1);
}

if ((semid = semget(SEM_KEY, 1, IPC_CREAT | 0666)) < 0) {


perror("semget");
exit(1);
}

arg.val = 1;
if (semctl(semid, 0, SETVAL, arg) < 0) {
perror("semctl");
exit(1);
}

if ((parent_shm = shmat(shmid, NULL, 0)) == (int *)-1) {


perror("parent shmat");
exit(1);
}

*parent_shm = 0;
if ((pid = fork()) < 0) {
printf("Child Process Creation Error:%d\n", errno);
return 0;
}

if (pid == 0) {

if ((child_shm = shmat(shmid, NULL, 0)) == (int *)-1) {


perror("child shmat");
exit(1);
}

for (i = 0; i < CHILD_INCREMENT_COUNT; i++) {

operations[0].sem_num = 0;
operations[0].sem_op = -1;
operations[0].sem_flg = 0;

if (semop(semid, operations, 1) < 0) {


perror("child semop");
exit(1);
}

*child_shm = *child_shm + 1;

if (i%1000 == 0) {
usleep(1); // sleep 1 us to increase window of critical section
}

operations[0].sem_num = 0;
operations[0].sem_op = 1;
operations[0].sem_flg = 0;

if (semop(semid, operations, 1) < 0) {


perror("child semop");
exit(1);
}

if (pid != 0) {

for (i = 0; i < PARENT_INCREMENT_COUNT; i++) {

operations[0].sem_num = 0;
operations[0].sem_op = -1;
operations[0].sem_flg = 0;

if (semop(semid, operations, 1) < 0) {


perror("parent semop");
exit(1);
}

*parent_shm = *parent_shm + 1;

if (i%1500 == 0) {
usleep(1); // sleep 1 us to increase window of critical section
}

operations[0].sem_num = 0;
operations[0].sem_op = 1;
operations[0].sem_flg = 0;
if (semop(semid, operations, 1) < 0) {
perror("parent semop");
exit(1);
}

// wait for child to complete


wait(&status);

printf("Child Incremented %d times, Parent %d times. SHM Value %d\n",


CHILD_INCREMENT_COUNT, PARENT_INCREMENT_COUNT, *parent_shm);
if (*parent_shm == (CHILD_INCREMENT_COUNT + PARENT_INCREMENT_COUNT)) {
printf("Total of Parent & Child matches SHM value\n");
} else {
printf("BUG - Total of Parent & Child DOESNT match SHM value\n");
}
}

exit(0);

OUTPUT:-

Week – 7
Aim :- Design TCP iterative Client and server application to reverse the given input sentence.
Description:
In this, first setup client-server connection. When connection will setup, client will send user input string to server by
send system call. At server side, server will wait for string sent by client. Server read string by read system call. After
this, server will reverse the string and send back to client.

PROGRAM : (CLIENT SIDE)

// C client code to send string to reverse


#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>

#define PORT 8090

int main()
{
struct sockaddr_in address;
int sock = 0, valread;
struct sockaddr_in serv_addr;
char str[100];

printf("\nInput the string:");


scanf("%[^\n]s", str);

char buffer[1024] = { 0 };

// Creating socket file descriptor


if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Socket creation error \n");
return -1;
}

memset(&serv_addr, '0', sizeof(serv_addr));


serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);

if (inet_pton(AF_INET, "127.0.0.1",
&serv_addr.sin_addr)
<= 0) {
printf("\nAddress not supported \n");
return -1;
}

// connect the socket


if (connect(sock, (struct sockaddr*)&serv_addr,
sizeof(serv_addr))
< 0) {
printf("\nConnection Failed \n");
return -1;
}

int l = strlen(str);

// send string to server side


send(sock, str, sizeof(str), 0);

// read string sent by server


valread = read(sock, str, l);

printf("%s\n", str);
return 0;
}

SERVERSIDE:-

// Server C code to reverse a


// string by sent from client
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>

#define PORT 8090

// Driver code
int main()
{
int server_fd, new_socket, valread;
struct sockaddr_in address;
char str[100];
int addrlen = sizeof(address);
char buffer[1024] = { 0 };
char* hello = "Hello from server";

// Creating socket file descriptor


if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}

address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);

if (bind(server_fd, (struct sockaddr*)&address, sizeof(address)) < 0) {


perror("bind failed");
exit(EXIT_FAILURE);
}

// puts the server socket in passive mode


if (listen(server_fd, 3) < 0) {
perror("listen");
exit(EXIT_FAILURE);
}
if ((new_socket = accept(server_fd,
(struct sockaddr*)&address,
(socklen_t*)&addrlen)) < 0) {
perror("accept");
exit(EXIT_FAILURE);
}

// read string send by client


valread = read(new_socket, str, sizeof(str));
int i, j, temp;
int l = strlen(str);

printf("\nString sent by client:%s\n", str);

// loop to reverse the string


for (i = 0, j = l - 1; i < j; i++, j--) {
temp = str[i];
str[i] = str[j];
str[j] = temp;
}

// send reversed string to client


// by send system call
send(new_socket, str, sizeof(str), 0);
printf("\nModified string sent to client\n");

return 0;
}

OUTPUT:-

Week-8
Aim :- Design TCP client and server application to transfer file.
Description :
TCP refers to the Transmission Control Protocol, which is a highly efficient and reliable protocol designed for
end-to-end data transmission over an unreliable network. 

A TCP connection uses a three-way handshake to connect the client and the server. It is a process that
requires both the client and the server to exchange synchronization (SYN) and acknowledge (ACK) packet
before the data transfer takes place.

The add.txt file contains the code for client-side, which read the text file and sends it to the server and the
add1.txt file receives the data from the client and saves it in a text file.

PROGRAM:-

SERVER SIDE:-

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <arpa/inet.h>

#define SIZE 1024

void write_file(int sockfd){

int n;

FILE *fp;

char *filename = "recv.txt";

char buffer[SIZE];

fp = fopen(filename, "w");

while (1) {

n = recv(sockfd, buffer, SIZE, 0);

if (n <= 0){

break;

return;

fprintf(fp, "%s", buffer);

bzero(buffer, SIZE);

}
return;

int main(){

char *ip = "127.0.0.1";

int port = 8080;

int e;

int sockfd, new_sock;

struct sockaddr_in server_addr, new_addr;

socklen_t addr_size;

char buffer[SIZE];

sockfd = socket(AF_INET, SOCK_STREAM, 0);

if(sockfd < 0) {

perror("[-]Error in socket");

exit(1);

printf("[+]Server socket created successfully.\n");

server_addr.sin_family = AF_INET;

server_addr.sin_port = port;

server_addr.sin_addr.s_addr = inet_addr(ip);

e = bind(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr));

if(e < 0) {

perror("[-]Error in bind");

exit(1);
}

printf("[+]Binding successfull.\n");

if(listen(sockfd, 10) == 0){

printf("[+]Listening....\n");

}else{

perror("[-]Error in listening");

exit(1);

addr_size = sizeof(new_addr);

new_sock = accept(sockfd, (struct sockaddr*)&new_addr, &addr_size);

write_file(new_sock);

printf("[+]Data written in the file successfully.\n");

return 0;

CLIENT SIDE :-

#include <stdio.h>

#include <stdlib.h>
#include <unistd.h>

#include <string.h>

#include <arpa/inet.h>

#define SIZE 1024

void send_file(FILE *fp, int sockfd){

int n;

char data[SIZE] = {0};

while(fgets(data, SIZE, fp) != NULL) {

if (send(sockfd, data, sizeof(data), 0) == -1) {

perror("[-]Error in sending file.");

exit(1);

bzero(data, SIZE);

int main(){

char *ip = "127.0.0.1";

int port = 8080;

int e;

int sockfd;

struct sockaddr_in server_addr;

FILE *fp;

char *filename = "add.txt";

sockfd = socket(AF_INET, SOCK_STREAM, 0);


if(sockfd < 0) {

perror("[-]Error in socket");

exit(1);

printf("[+]Server socket created successfully.\n");

server_addr.sin_family = AF_INET;

server_addr.sin_port = port;

server_addr.sin_addr.s_addr = inet_addr(ip);

e = connect(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr));

if(e == -1) {

perror("[-]Error in socket");

exit(1);

printf("[+]Connected to Server.\n");

fp = fopen(filename, "r");

if (fp == NULL) {

perror("[-]Error in reading file.");

exit(1);

send_file(fp, sockfd);

printf("[+]File data sent successfully.\n");

printf("[+]Closing the connection.\n");

close(sockfd);
return 0;

OUTPUT:-

WEEK-9
AIM:- Design UDP Client and server application to reverse the given input sentence.
DESCRIPTION: The TCP/IP protocol suite provides two transport protocols, the User Datagram
Protocol (UDP) described in this chapter, and the Transmission Control Protocol (TCP).There are
some fundamental differences between applications written using TCP versus those that use UDP.
 First setup client-server connection. When connection will setup, client will send user input string
to server by send system call. At server side, server will wait for string sent by client. Server read
string by read system call. After this, server will reverse the string and send back to client.
PROGRAM:-

CLIENT SIDE:-
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>

#define S_PORT 43454


#define C_PORT 43455
#define ERROR -1
#define IP_STR "127.0.0.1"

int main(int argc, char const *argv[]) {


int sfd, len;
char str_buf[2048];
struct sockaddr_in servaddr, clientaddr;
socklen_t addrlen;
sfd = socket(AF_INET, SOCK_DGRAM,IPPROTO_UDP);
if (sfd == ERROR) {
perror("Could not open a socket");
return 1;
}
memset((char *) &servaddr, 0, sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=inet_addr(IP_STR);
servaddr.sin_port=htons(S_PORT);

memset((char *) &clientaddr, 0, sizeof(clientaddr));


clientaddr.sin_family=AF_INET;
clientaddr.sin_addr.s_addr=inet_addr(IP_STR);
clientaddr.sin_port=htons(C_PORT);

if((bind(sfd,(struct sockaddr *)&clientaddr,sizeof(clientaddr)))!=0) {


perror("Could not bind socket");
return 2;
}

printf("Client is running on %s:%d\n", IP_STR, C_PORT);


printf("Enter a string: ");
scanf("%[^\n]%*c",str_buf);
len = strlen(str_buf);
sendto(sfd, &len, sizeof(len), 0, (struct sockaddr *)&servaddr, sizeof(servaddr));
sendto(sfd, str_buf, len, 0, (struct sockaddr *)&servaddr, sizeof(servaddr));
addrlen = sizeof(clientaddr);
recvfrom(sfd, &len, sizeof(len), 0, (struct sockaddr *)&clientaddr, &addrlen);
recvfrom(sfd, str_buf, len, 0, (struct sockaddr *)&clientaddr, &addrlen);
printf("Server Replied: %s\n", str_buf);

return 0;
}

SERVER SIDE:
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>

#define S_PORT 43454


#define C_PORT 43455
#define ERROR -1
#define IP_STR "127.0.0.1"

void strrev(char *str, int len) {


int i, j;
char temp;
for (i = 0, j = len -1; i < j; ++i, --j) {
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}

int main(int argc, char const *argv[]) {


int sfd, len;
char *str_buf;
struct sockaddr_in servaddr, clientaddr;
sfd = socket(AF_INET, SOCK_DGRAM,IPPROTO_UDP);
if (sfd == ERROR) {
perror("Could not open a socket");
return 1;
}
memset((char *) &servaddr, 0, sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
servaddr.sin_port=htons(S_PORT);

memset((char *) &clientaddr, 0, sizeof(clientaddr));


clientaddr.sin_family=AF_INET;
clientaddr.sin_addr.s_addr=inet_addr(IP_STR);
clientaddr.sin_port=htons(C_PORT);

if((bind(sfd,(struct sockaddr *)&servaddr,sizeof(servaddr)))!=0) {


perror("Could not bind socket");
return 2;
}

printf("Server is running on %s:%d\n", IP_STR, S_PORT);


while(1) {
recvfrom(sfd, &len, sizeof(len), 0, (struct sockaddr *)&clientaddr, (socklen_t
*)&clientaddr);
str_buf = (char *) malloc(len*sizeof(char));
recvfrom(sfd, str_buf, len, 0, (struct sockaddr *)&clientaddr, (socklen_t
*)&clientaddr);
printf("Client at %s:%d said: %s\t", inet_ntoa(clientaddr.sin_addr),
ntohs(clientaddr.sin_port), str_buf);
strrev(str_buf,len);
sendto(sfd, &len, sizeof(len), 0, (struct sockaddr *)&clientaddr, sizeof(clientaddr));
sendto(sfd, str_buf, len, 0, (struct sockaddr *)&clientaddr, sizeof(clientaddr));
printf("The reverse is: %s\n", str_buf);
free(str_buf);
}
return 0;
}

OUTPUT:-

Week 10:
Aim : Design UDP client server to transfer a file.
Description :
The UDP client and server are created with the help of DatagramSocket and Datagram packet
classes. If the UDP protocol is used at transport, then the unit of data at the transport layer is called
a datagram and and not a segment. In UDP, no connection is established. It is the responsibility of
an application to encapsulate data in datagrams (using Datagram classes) before sending it. If TCP
is used for sending data, then the data is written directly to the socket (client or server) and reaches
there as a connection exists between them. The datagram sent by the application using UDP may or
may not reach the UDP receiver.
PROGRAM:-
Server side:
// server code for UDP socket programming
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>

#define IP_PROTOCOL 0
#define PORT_NO 15050
#define NET_BUF_SIZE 32
#define cipherKey 'S'
#define sendrecvflag 0
#define nofile "File Not Found!"

// function to clear buffer


void clearBuf(char* b)
{
int i;
for (i = 0; i < NET_BUF_SIZE; i++)
b[i] = '\0';
}

// function to encrypt
char Cipher(char ch)
{
return ch ^ cipherKey;
}

// function sending file


int sendFile(FILE* fp, char* buf, int s)
{
int i, len;
if (fp == NULL) {
strcpy(buf, nofile);
len = strlen(nofile);
buf[len] = EOF;
for (i = 0; i <= len; i++)
buf[i] = Cipher(buf[i]);
return 1;
}

char ch, ch2;


for (i = 0; i < s; i++) {
ch = fgetc(fp);
ch2 = Cipher(ch);
buf[i] = ch2;
if (ch == EOF)
return 1;
}
return 0;
}

// driver code
int main()
{
int sockfd, nBytes;
struct sockaddr_in addr_con;
int addrlen = sizeof(addr_con);
addr_con.sin_family = AF_INET;
addr_con.sin_port = htons(PORT_NO);
addr_con.sin_addr.s_addr = INADDR_ANY;
char net_buf[NET_BUF_SIZE];
FILE* fp;

// socket()
sockfd = socket(AF_INET, SOCK_DGRAM, IP_PROTOCOL);

if (sockfd < 0)
printf("\nfile descriptor not received!!\n");
else
printf("\nfile descriptor %d received\n", sockfd);

// bind()
if (bind(sockfd, (struct sockaddr*)&addr_con, sizeof(addr_con)) == 0)
printf("\nSuccessfully binded!\n");
else
printf("\nBinding Failed!\n");

while (1) {
printf("\nWaiting for file name...\n");

// receive file name


clearBuf(net_buf);

nBytes = recvfrom(sockfd, net_buf,


NET_BUF_SIZE, sendrecvflag,
(struct sockaddr*)&addr_con, &addrlen);

fp = fopen(net_buf, "r");
printf("\nFile Name Received: %s\n", net_buf);
if (fp == NULL)
printf("\nFile open failed!\n");
else
printf("\nFile Successfully opened!\n");
while (1) {

// process
if (sendFile(fp, net_buf, NET_BUF_SIZE)) {
sendto(sockfd, net_buf, NET_BUF_SIZE,
sendrecvflag,
(struct sockaddr*)&addr_con, addrlen);
break;
}

// send
sendto(sockfd, net_buf, NET_BUF_SIZE,
sendrecvflag,
(struct sockaddr*)&addr_con, addrlen);
clearBuf(net_buf);
}
if (fp != NULL)
fclose(fp);
}
return 0;
}

Client side:-
// client code for UDP socket programming
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>

#define IP_PROTOCOL 0
#define IP_ADDRESS "127.0.0.1" // localhost
#define PORT_NO 15050
#define NET_BUF_SIZE 32
#define cipherKey 'S'
#define sendrecvflag 0

// function to clear buffer


void clearBuf(char* b)
{
int i;
for (i = 0; i < NET_BUF_SIZE; i++)
b[i] = '\0';
}

// function for decryption


char Cipher(char ch)
{
return ch ^ cipherKey;
}

// function to receive file


int recvFile(char* buf, int s)
{
int i;
char ch;
for (i = 0; i < s; i++) {
ch = buf[i];
ch = Cipher(ch);
if (ch == EOF)
return 1;
else
printf("%c", ch);
}
return 0;
}

// driver code
int main()
{
int sockfd, nBytes;
struct sockaddr_in addr_con;
int addrlen = sizeof(addr_con);
addr_con.sin_family = AF_INET;
addr_con.sin_port = htons(PORT_NO);
addr_con.sin_addr.s_addr = inet_addr(IP_ADDRESS);
char net_buf[NET_BUF_SIZE];
FILE* fp;

// socket()
sockfd = socket(AF_INET, SOCK_DGRAM,
IP_PROTOCOL);

if (sockfd < 0)
printf("\nfile descriptor not received!!\n");
else
printf("\nfile descriptor %d received\n", sockfd);

while (1) {
printf("\nPlease enter file name to receive:\n");
scanf("%s", net_buf);
sendto(sockfd, net_buf, NET_BUF_SIZE,
sendrecvflag, (struct sockaddr*)&addr_con,
addrlen);

printf("\n---------Data Received---------\n");

while (1) {
// receive
clearBuf(net_buf);
nBytes = recvfrom(sockfd, net_buf, NET_BUF_SIZE,
sendrecvflag, (struct sockaddr*)&addr_con,
&addrlen);

// process
if (recvFile(net_buf, NET_BUF_SIZE)) {
break;
}
}
printf("\n-------------------------------\n");
}
return 0;
}
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: Poll is used for multiplexing tcp & udp requests
#include<poll.h>
int poll ( struct pollfd *fdarray, unsigned long nfds, int timeout);
getsockopt and setsockopt Functions
#include <sys/socket.h>
Int getsockopt (int sockfd, int level, int optname, void *optval, socklen_t *optlen);
Int setsockopt (int sockfd, int level, int optname, void *optval, socklen_t *optlen);
Both return : 0 if ok, -1 on error.
1) Sockfd from socket descriptor.
2) The level specifies the code in the system to interpret the option.
3) The optval is a pointer to a variable, can be set true(non-zero) or false(zero).
4) Size of the third argument variable.

PROGRAM:

CLIENT PROGRAM:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<unistd.h>
#include<netinet/in.h>
#define MAXLINE 20
#define SERV_PORT 8114
main(int argc,char **argv)
{
int maxfdp1;
fd_set rset;
char sendline[MAXLINE],recvline[MAXLINE];
int sockfd;
struct sockaddr_in servaddr;
if(argc!=2)
{
printf("usage tcpcli <ipaddress>");
return;
}
sockfd=socket(AF_INET,SOCK_STREAM,0);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(SERV_PORT);
inet_pton(AF_INET,argv[1],&servaddr.sin_addr);
connect(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
printf("\nenter data to be send:");
while(fgets(sendline,MAXLINE,stdin)!=NULL)
{
write(sockfd,sendline,MAXLINE);
printf("\nline send to server :%s ",sendline);
read(sockfd,recvline,MAXLINE);
printf("line received from the server : %s",recvline);
}
exit(0);
}

SERVER PROGRAM:

#include<stdio.h>
#include<netinet/in.h>
#include<sys/types.h>
#include<string.h>
#include<stdlib.h>
#include<sys/socket.h>
#include<sys/select.h>
#include<unistd.h>
#define MAXLINE 20
#define SERV_PORT 8114
main(int argc,char **argv)
{
int i,j,maxi,maxfd,listenfd,connfd,sockfd;
int nready,client[FD_SETSIZE];
ssize_t n;
fd_set rset,allset;
char line[MAXLINE];
socklen_t clilen;
struct sockaddr_in cliaddr,servaddr;
listenfd=socket(AF_INET,SOCK_STREAM,0);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
servaddr.sin_port=htons(SERV_PORT);
bind(listenfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
listen(listenfd,1);
maxfd=listenfd;
maxi=-1;
for(i=0;i<FD_SETSIZE;i++)
client[i]=-1;
FD_ZERO(&allset);
FD_SET(listenfd,&allset);
for(;;)
{
rset=allset;
nready=select(maxfd+1,&rset,NULL,NULL,NULL);
if(FD_ISSET(listenfd,&rset))
{
clilen=sizeof(cliaddr);
connfd=accept(listenfd,(struct sockaddr *)&cliaddr,&clilen);
for(i=0;i<FD_SETSIZE;i++)
if(client[i]<0)
{
client[i]=connfd;
break;
}
if(i==FD_SETSIZE)
{
printf("too many clients");
exit(0);
}
FD_SET(connfd,&allset);
if(connfd>maxfd)
maxfd=connfd;
if(i>maxi)
maxi=i;
if(--nready<=0)
continue;
}
for(i=0;i<=maxi;i++)
{
if((sockfd=client[i])<0)
continue;
if(FD_ISSET(sockfd,&rset))
{
if((n=read(sockfd,line,MAXLINE))==0)
{
close(sockfd);
FD_CLR(sockfd,&allset);
client[i]=-1;
}
else
{
printf("line received from client:%s\n",line);
for(j=0;line[j]!='\0';j++)
line[j]=toupper(line[j]);
write(sockfd,line,MAXLINE);
}
if(--nready<=0)
break;
}
}
}
}

OUTPUT:

You might also like