This code creates a TCP socket server that can communicate with multiple clients simultaneously. An efficient method to simultaneously control several victims...
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <fcntl.h>
#include <errno.h>
#CODE BY E1.Coders
#define PORT 8888
#define CLIENTS 5
int main() {
int server_fd, new_socket, client_socket[CLIENTS], activity, i, valread, sd;
int max_sd;
struct sockaddr_in address;
char buffer[1025];
fd_set readfds;
char *message = "ECHO Daemon v1.0 \r\n";
for (i = 0; i < CLIENTS; i++) {
client_socket[i] = 0;
}
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
fcntl(server_fd, F_SETFL, O_NONBLOCK);
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);
}
printf("Listener on port %d \n", PORT);
if (listen(server_fd, 3) < 0) {
perror("listen");
exit(EXIT_FAILURE);
}
while (TRUE) {
FD_ZERO(&readfds);
FD_SET(server_fd, &readfds);
max_sd = server_fd;
for (i = 0; i < CLIENTS; i++) {
sd = client_socket[i];
if (sd > 0)
FD_SET(sd, &readfds);
if (sd > max_sd)
max_sd = sd;
}
activity = select(max_sd + 1, &readfds, NULL, NULL, NULL);
if ((activity < 0) && (errno != EINTR)) {
printf("select error");
}
if (FD_ISSET(server_fd, &readfds)) {
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t *)&addrlen)) < 0) {
perror("accept");
exit(EXIT_FAILURE);
}
if (send(new_socket, message, strlen(message), 0) != strlen(message)) {
perror("send");
}
puts("Welcome message sent successfully");
for (i = 0; i < CLIENTS; i++) {
if (client_socket[i] == 0) {
client_socket[i] = new_socket;
printf("Adding to list of sockets as %d\n", i);
break;
}
}
} for (i = 0; i < CLIENTS; i++) {
sd = client_socket[i];
if (FD_ISSET(sd, &readfds)) {
if ((valread = read(sd, buffer, 1024)) == 0) {
getpeername(sd, (struct sockaddr *)&address, (socklen_t *)&addrlen);
printf("Host disconnected, ip %s, port %d \n", inet_ntoa(address.sin_addr), ntohs(address.sin_port));
close(sd);
client_socket[i] = 0;
}
else {
buffer[valread] = '\0';
send(sd, buffer, strlen(buffer), 0);
}
}
}
}
return 0;
}