Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 3

Lab Experiment:

Write a Program in C using sockets depicting the following scenario:

The client requests for a file. The server opens the file, if it exists and transfers the contents of the file to
the client. The client displays the contents of the file received on the console.

Flow:-

Client Server

Create_socket
Create_socket

Bind_socket

Listen

Connect_socket

Accept connection

Take filename from user send(Filename)

Recv(Filename)

OpenFile(Filename)

Send(contentsOfFile) ReadFile

Recv(contentsOfFile)

Close_socket

DisplayOnConsole(contentsOfFile)

Close_socket
PROCEDURE:

Header files to be included:


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

/*server.c*/
1. Create a socket
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) printf("ERROR opening socket");
else printf(“Socket was created\n”);
2. Bind the socket to an address
Struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_port = htons(15000);
bind(sockfd, (struct sockaddr *) & addr, sizeof(addr);
3. Listen for connections
listen(sockfd,5);
4. Accept a connection
int addrlen = sizeof(struct sockaddr_in)
int newsockfd = accept(sockfd, (struct sockaddr *) & addr,&addrlen);
5. Send and receive data
recv(newsockfd, fname,255,0)
/* open the file */
int fd= open(fname, O_RDONLY)
/* read and send the contents of the file */
int cont,bufsize=1024; char * buffer = malloc(bufsize);
while((cont = read(fd,buffer,bufsize)) >0)
send(newsockfd,buffer,cont,0);
6 /* close the connection */
Close(sockfd);
Close(newsockfd);

/* client.c */
1. Create a socket
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) printf("ERROR opening socket");
2. Connect the socket to the address of the server
Struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(15000);
inet_pton(AF_INET,argv[1],&addr.sin_addr);

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


3. Send and receive data
send(sockfd, fname, sizeof(fname),0);
/* receive the file contents from server and write to console */
while((cont = recv(sockfd, buffer, bufsize,0)) > 0)
write(1, buffer,cont);

4. /* close the connection */


Close(sockfd);

You might also like