// Server side program
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int serv_sockfd, cli_sockfd;
socklen_t serv_len, cli_len;
struct sockaddr_in serv_address, cli_address;
char a[100], b[100];
// Create socket
serv_sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (serv_sockfd < 0) {
perror("Socket creation failed");
exit(1);
}
// Set up the server address struct
serv_address.sin_family = AF_INET;
serv_address.sin_port = htons(9001);
serv_address.sin_addr.s_addr = inet_addr("127.0.0.1");
serv_len = sizeof(serv_address);
// Bind the socket to the specified IP and port
if (bind(serv_sockfd, (struct sockaddr*) &serv_address, serv_len) < 0) {
perror("Bind failed");
close(serv_sockfd);
exit(1);
}
// Listen for incoming connections
if (listen(serv_sockfd, 5) < 0) {
perror("Listen failed");
close(serv_sockfd);
exit(1);
}
while (1)
{
printf("SERVER IS WAITING...\n");
cli_len = sizeof(cli_address);
// Accept a connection from a client
cli_sockfd = accept(serv_sockfd, (struct sockaddr*) &cli_address, &cli_len);
if (cli_sockfd < 0) {
perror("Accept failed");
continue;
}
// Read message from client
memset(a, 0, sizeof(a));
read(cli_sockfd, a, sizeof(a));
printf("Reading message from client: %s\n", a);
// Send message to client
printf("Enter the message for client: ");
fgets(b, sizeof(b), stdin);
write(cli_sockfd, b, strlen(b) + 1);
// Close the client socket
close(cli_sockfd);
}
// Close the server socket
close(serv_sockfd);
return 0;
}
0 Comments