diff options
| author | 2026-09-23 21:05:50 +0000 | |
|---|---|---|
| committer | 2026-09-23 21:06:06 +0000 | |
| commit | 4d45a67b92ed7d85f8df6ca0ed55b2c5b0db983d (patch) | |
| tree | 0a829a42efcc9678d89e6af7e8feb43f5c553cb1 /src/main.c | |
| parent | 4770fad02e7f2c57a2644dc083add8a465ca521a (diff) | |
servidor de echo completo
Diffstat (limited to 'src/main.c')
| -rw-r--r-- | src/main.c | 71 |
1 files changed, 52 insertions, 19 deletions
@@ -5,51 +5,84 @@ #include<netdb.h> #include<string.h> #include<stdlib.h> +#include<unistd.h> #include<errno.h> -int -main() +#define ADDR NULL +#define PORT "9123" +#define BUFSIZE 32 + +int main() { - int gai_status, b_status; - int socketfd; + int gai_status, b_status, l_status; + int sockfd, accepted_sockfd; struct addrinfo hints, *res; - char ipstr[INET6_ADDRSTRLEN]; + struct sockaddr_storage incoming_addr; + socklen_t addr_size; + char* buf[BUFSIZE]; + ssize_t bytes_read, bytes_sent; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; - gai_status = getaddrinfo(NULL, "9123", &hints, &res); - if (gai_status != 0) - { + gai_status = getaddrinfo(ADDR, PORT, &hints, &res); + if (gai_status != 0) { fprintf(stderr, "gai error: %s\n", gai_strerror(gai_status)); exit(1); } - socketfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol); - if (socketfd < 0) - { + sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol); + if (sockfd < 0) { fprintf(stderr, "socket error: %d\n", errno); exit(1); } - b_status = bind(socketfd, res->ai_addr, res->ai_addrlen); - if (b_status < 0) - { + int yes = 1; + setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof yes); + + b_status = bind(sockfd, res->ai_addr, res->ai_addrlen); + if (b_status < 0) { fprintf(stderr, "bind error: %d\n", errno); exit(1); } - inet_ntop(res->ai_family, &(((struct sockaddr_in *) res->ai_addr)->sin_addr), ipstr, sizeof ipstr); - if (ipstr == NULL) - { - fprintf(stderr, "string error: %d\n", errno); + l_status = listen(sockfd, 5); + if (l_status < 0) { + fprintf(stderr, "listen error: %d\n", errno); exit(1); } - printf("Endereço: %s", ipstr); + while (1) { + addr_size = sizeof incoming_addr; + accepted_sockfd = + accept(sockfd, (struct sockaddr *)&incoming_addr, &addr_size); + if (accepted_sockfd < 0) { + fprintf(stderr, "accept socket error: %d\n", errno); + exit(1); + } + + while (1) { + bytes_read = recv(accepted_sockfd, &buf, BUFSIZE, 0); + /* Sem mais bytes para ler */ + if (bytes_read == 0) { + break; + } else if (bytes_read < 0) { + fprintf(stderr, "recv error: %d\n", errno); + exit(1); + } + + bytes_sent = send(accepted_sockfd, buf, bytes_read, 0); + if (bytes_sent < 0) { + fprintf(stderr, "send error: %d\n", errno); + exit(1); + } + } + } + close(accepted_sockfd); + close(sockfd); freeaddrinfo(res); return 0; |
