/* usamos isso pra ter acesso ao `getaddrinfo()` e similares */ /* sera que da pra programar sockets sem usar? */ #ifndef _POSIX_C_SOURCE #define _POSIX_C_SOURCE 200112L #endif #include #include #include #include #include #include #include #include #include #define ADDR NULL #define PORT "9123" #define BUFSIZE 32 #define BACKLOG 10 int main() { int gai_status, so_status, bind_status, listen_status, sockfd; struct addrinfo hints = { .ai_family = AF_UNSPEC, .ai_socktype = SOCK_STREAM, }; struct addrinfo *res; gai_status = getaddrinfo(ADDR, PORT, &hints, &res); if (gai_status != 0) { fprintf(stderr, "gai error: %s.\n", gai_strerror(gai_status)); exit(1); } sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol); if (sockfd < 0) { fprintf(stderr, "socket error: %d.\n", errno); exit(1); } /* nao tem uma maneira boa de explicar isso. essas linhas garantem que o * mesmo socket possa ser reutilizado sem erros de bind. */ int yes = 1; so_status = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof yes); if (so_status < 0) { fprintf(stderr, "sockopt error: %d.\n", errno); exit(1); } bind_status = bind(sockfd, res->ai_addr, res->ai_addrlen); if (bind_status < 0) { fprintf(stderr, "bind error: %d.\n", errno); exit(1); } listen_status = listen(sockfd, BACKLOG); if (listen_status < 0) { fprintf(stderr, "listen error: %d.\n", errno); exit(1); } /* loop principal: fica ouvindo conexões que chegam na porta PORT */ while (1) { int client_sockfd = accept(sockfd, res->ai_addr, &res->ai_addrlen); if (client_sockfd < 0) { fprintf(stderr, "accept error: %d.\n", errno); exit(1); } char buf[BUFSIZE]; while (1) { ssize_t msg_len = recv(client_sockfd, buf, BUFSIZE, 0); if (msg_len < 0) { fprintf(stderr, "recv error: %d.\n", errno); exit(1); } else if (msg_len == 0) { /* sem mais bytes a receber */ break; } ssize_t sent_len = send(client_sockfd, buf, msg_len, 0); if (sent_len < 0) { fprintf(stderr, "send error: %d.\n", errno); exit(1); } } } freeaddrinfo(res); return 0; }