#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define PORT 13400 // Change the listening port here
#define MAX_CLIENTS 20 // Change the maximum number of clients here
int main()
{
int server_fd, client_fd[MAX_CLIENTS], max_fd, activity, valread;
struct sockaddr_in address;
char buffer[1024] = {0};
fd_set read_fds;
// Create server socket
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0)
{
perror("socket failed");
exit(EXIT_FAILURE);
}
// Set server socket options
int opt = 1;
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0)
{
perror("setsockopt failed");
exit(EXIT_FAILURE);
}
// Bind server socket to port
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);
}
// Listen for incoming connections
if (listen(server_fd, 3) < 0)
{
perror("listen failed");
exit(EXIT_FAILURE);
}
// Accept incoming connections
int addrlen = sizeof(address);
for (int i = 0; i < MAX_CLIENTS; i++)
{
if ((client_fd[i] = accept(server_fd, (struct sockaddr *)&address, (socklen_t *)&addrlen)) < 0)
{
perror("accept failed");
exit(EXIT_FAILURE);
}
}
// Initialize file descriptor set
FD_ZERO(&read_fds);
max_fd = server_fd;
for (int i = 0; i < MAX_CLIENTS; i++)
{
FD_SET(client_fd[i], &read_fds);
if (client_fd[i] > max_fd)
max_fd = client_fd[i];
}
// Process data from clients
while (1)
{ // Check each client socket for input
activity = select(max_fd + 1, &read_fds, NULL, NULL, NULL);
if (activity < 0)
{ perror("select failed");
exit(EXIT_FAILURE); }
// Handle input from each client
for (int i = 0; i < MAX_CLIENTS; i++)
{
if (FD_ISSET(client_fd[i], &read_fds))
{
valread = read(client_fd[i], buffer, sizeof(buffer));
if (valread <= 0)
{
// Connection closed by client
close(client_fd[i]);
FD_CLR(client_fd[i], &read_fds);
}
else
{
// Handle input from client
printf("Received message from client %d: %s\n", i, buffer);
// Process input from client
// ...
}
}
}
}
return 0;