#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#define PORT 8080
#define MAX_BUFFER_SIZE 1024
int main() {
int server_socket, client_socket;
struct sockaddr_in server_addr, client_addr;
char buffer[MAX_BUFFER_SIZE];
if ((server_socket = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("Erro ao criar o socket");
exit(EXIT_FAILURE);
}
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(PORT);
if (bind(server_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
perror("Erro ao associar o socket ao endereço");
exit(EXIT_FAILURE);
}
if (listen(server_socket, 5) == -1) {
perror("Erro ao colocar o socket em modo de escuta");
exit(EXIT_FAILURE);
}
printf("Servidor escutando na porta %d...\n", PORT);
socklen_t client_addr_len = sizeof(client_addr);
if ((client_socket = accept(server_socket, (struct sockaddr*)&client_addr, &client_addr_len)) == -1) {
perror("Erro ao aceitar a conexão do cliente");
exit(EXIT_FAILURE);
}
printf("Cliente conectado: %s\n", inet_ntoa(client_addr.sin_addr));
while (1) {
ssize_t bytes_received = recv(client_socket, buffer, MAX_BUFFER_SIZE, 0);
if (bytes_received <= 0) {
printf("Conexão encerrada pelo cliente.\n");
break;
}
printf("Recebido: %s", buffer);
send(client_socket, buffer, bytes_received, 0);
memset(buffer, 0, sizeof(buffer));
}
close(client_socket);
close(server_socket);
return 0;
}