aboutsummaryrefslogtreecommitdiff
path: root/src/main.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/main.c')
-rw-r--r--src/main.c71
1 files changed, 52 insertions, 19 deletions
diff --git a/src/main.c b/src/main.c
index 1c5c6ff..f5ddb94 100644
--- a/src/main.c
+++ b/src/main.c
@@ -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;