From a9864542b36e586f683dfaab9ee295cb10d1ce95 Mon Sep 17 00:00:00 2001 From: Stephen Seo Date: Fri, 6 Sep 2024 13:11:00 +0900 Subject: [PATCH] Add README.md, ensure listening port is printed --- README.md | 26 ++++++++++++++++++++++++++ src/main.c | 17 +++++++++++++++-- 2 files changed, 41 insertions(+), 2 deletions(-) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 0000000..71d081a --- /dev/null +++ b/README.md @@ -0,0 +1,26 @@ +# C Simple HTTP + +A simple HTTP/1.1 server written in C. + +## Usage + + Usage: + -p | --port + --config= + +## Example + + # Build the project. + make c_simple_http + + # Run it with the example config. + ./c_simple_http --config=example_config/example.config + + # If port is not specified, the server picks a random port. + # This program should print which TCP port it is listening on. + # Sometimes the program will fail to rebind to the same port due to how TCP + # works. Either wait some time or choose a different port. + + # Access the website. + # This assumes the server is hosted on port 3000. + curl localhost:3000 diff --git a/src/main.c b/src/main.c index de9211b..17ab294 100644 --- a/src/main.c +++ b/src/main.c @@ -48,8 +48,7 @@ int main(int argc, char **argv) { return 2; } - printf("listening on port: %u\n", args.port); - printf("config file is: %s\n", args.config_file); + printf("Config file is: %s\n", args.config_file); __attribute__((cleanup(c_simple_http_clean_up_parsed_config))) C_SIMPLE_HTTP_ParsedConfig parsed_config = c_simple_http_parse_config( @@ -64,6 +63,20 @@ int main(int argc, char **argv) { return 1; } + { + struct sockaddr_in6 ipv6_addr; + memset(&ipv6_addr, 0, sizeof(struct sockaddr_in6)); + socklen_t size = sizeof(ipv6_addr); + int ret = getsockname(tcp_socket, (struct sockaddr*)&ipv6_addr, &size); + if (ret == 0) { + printf("Listening on port: %u\n", u16_be_swap(ipv6_addr.sin6_port)); + } else { + fprintf( + stderr, + "WARNING Failed to get info on tcp socket to print port number!\n"); + } + } + struct timespec sleep_time; sleep_time.tv_sec = 0; sleep_time.tv_nsec = C_SIMPLE_HTTP_SLEEP_NANOS;