Professional Documents
Culture Documents
Socket Labexpt
Socket Labexpt
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
Recv(Filename)
OpenFile(Filename)
Send(contentsOfFile) ReadFile
Recv(contentsOfFile)
Close_socket
DisplayOnConsole(contentsOfFile)
Close_socket
PROCEDURE:
/*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);