Mercurial > public > hey
changeset 4:691358f944e8
remove hardcoded host info
author | Dennis <dennisconcepcionmartin@gmail.com> |
---|---|
date | Tue, 18 Jul 2023 12:04:37 +0100 |
parents | e96eaa6b74c1 |
children | 45bac89a4da3 |
files | src/main.c |
diffstat | 1 files changed, 28 insertions(+), 12 deletions(-) [+] |
line wrap: on
line diff
--- a/src/main.c Mon Jul 17 19:16:47 2023 +0100 +++ b/src/main.c Tue Jul 18 12:04:37 2023 +0100 @@ -1,9 +1,11 @@ #include <signal.h> #include <stdio.h> #include <stdlib.h> +#include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> +#include <netdb.h> #include <netinet/in.h> #include <arpa/inet.h> #include <time.h> @@ -15,42 +17,56 @@ void sig_handler(int sig_num) { if (sig_num == 2) { printf("\nClosing socket\n"); - shutdown(socketfd, 2); + close(socketfd); exit(0); } } int main() { + signal(SIGINT, sig_handler); - socketfd = socket(AF_INET, SOCK_STREAM, 0); + + struct addrinfo hints; + struct addrinfo *servinfo; + + memset(&hints, 0, sizeof hints); // Make sure the struct is empty + hints.ai_family = AF_UNSPEC; // Don't care IPv4 or IPv6 + hints.ai_socktype = SOCK_STREAM; // TCP stream sockets + hints.ai_flags = AI_PASSIVE; // Fill in my IP for me + + if ((getaddrinfo(NULL, "5050", &hints, &servinfo)) != 0) { + perror("getaddrinfo: "); + exit(1); + } + + socketfd = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol); if (socketfd == -1) { perror("socket: "); exit(1); } - struct sockaddr_in sin; - memset(&sin, 0, sizeof(sin)); - sin.sin_family = AF_INET; - sin.sin_addr.s_addr = inet_addr("127.0.0.1"); - sin.sin_port = htons(5050); - - if (bind(socketfd, (struct sockaddr*)&sin, sizeof(sin)) == -1) { + if (bind(socketfd, servinfo->ai_addr, servinfo->ai_addrlen) == -1) { perror("bind: "); exit(1); } + freeaddrinfo(servinfo); + if (listen(socketfd, 10) == -1) { perror("listen: "); exit(1); } + char send_buffer[100]; + struct sockaddr_storage clientinfo; + socklen_t clientinfo_size; + printf("Waiting for connections...\n"); - char send_buffer[100]; while (1) { - int connfd = accept(socketfd, (struct sockaddr*)NULL, NULL); + int connfd = accept(socketfd, (struct sockaddr *)&clientinfo, &clientinfo_size); if (connfd == -1) { perror("accept: \n"); @@ -60,7 +76,7 @@ time_t now = time(NULL); snprintf(send_buffer, sizeof(send_buffer), "Server time: %s\n", ctime(&now)); send(connfd, send_buffer, sizeof(send_buffer), 0); - shutdown(connfd, 2); + close(connfd); } return 0;