#include #include #include #include #include #include #include #include #include #include #include "lfnetwork.h" static void sighandler(int s) { int saved_errno = errno; while (waitpid(-1, NULL, WNOHANG) > 0); errno = saved_errno; } void *get_in_addr(struct sockaddr *sa) { if (sa->sa_family == AF_INET) { return &(((struct sockaddr_in*)sa)->sin_addr); } return &(((struct sockaddr_in6*)sa)->sin6_addr); } Server *new_server(ServerType type, const char *port, void(handler)(Server *s)) { Server *s = (Server *)malloc(sizeof(Server)); if (s == NULL) { return NULL; } s->server_type = type; s->handler = handler; struct addrinfo *addr = NULL; if (getaddrinfo(NULL, port, NULL, &addr) != 0) { free(s); return NULL; } s->port = (int)strtol(port, NULL, 10); int socktype = 0; switch (type) { case SERVERTYPE_TCP: socktype = SOCK_STREAM; break; case SERVERTYPE_UDP: socktype = SOCK_DGRAM; break; } struct addrinfo *p; for (p = addr; p != NULL; p = p->ai_next) { s->fd = socket(AF_INET, socktype, 0); if (s->fd == -1) { continue; } if (bind(s->fd, p->ai_addr, p->ai_addrlen) != 0) { close(s->fd); continue; } break; } if (p == NULL) { fprintf(stderr, "Failed to bind\n"); free(s); return NULL; } freeaddrinfo(addr); return s; } void delete_server(Server *s) { free(s); s = NULL; } int serve(Server *s, int backlog_size) { if (listen(s->fd, backlog_size) != 0) { return 1; } struct sigaction sa; sa.sa_handler = sighandler; sa.sa_flags = SA_RESTART; if (sigaction(SIGCHLD, &sa, NULL) == -1) { fprintf(stderr, "Failed to set sigaction\n"); return 1; } printf("Server is waiting for connections on port %d...\n", s->port); s->handler(s); return 0; } void handler_tcp_echo(Server *s) { struct sockaddr_storage client_addr; while (1) { socklen_t client_addr_sz = sizeof(client_addr); int new_fd = accept(s->fd, (struct sockaddr *)&client_addr, &client_addr_sz); if (new_fd == -1) { printf("failed to accept. Errno: %d\n", errno); continue; } char buf[33]; inet_ntop(client_addr.ss_family, get_in_addr((struct sockaddr *)&client_addr), buf, 32); printf("Received connection from %s\n", buf); // Start child process if (!fork()) { close(s->fd); // Child doesn't need the initial socket if (send(new_fd, "Hello, world!", 13, 0) == -1) { fprintf(stderr, "Failed to send hello world\n"); } close(new_fd); _exit(0); } // End child process close(new_fd); // new_fd is not used by the parent } }