diff options
-rw-r--r-- | Makefile | 4 | ||||
-rw-r--r-- | listen.c | 36 |
2 files changed, 23 insertions, 17 deletions
@@ -1,5 +1,5 @@ -CC=egcc -CFLAGS_TESTBIN=-O3 -Wfatal-errors -Wall -Werror -Wextra -g -Wpedantic -std=gnu99 +CC=gcc +CFLAGS_TESTBIN=-Og -fsanitize=address -Wfatal-errors -Wall -Werror -Werror=return-type -Wextra -g -Wpedantic -std=gnu99 CFLAGS=-O3 -flto -march=native -DNDEBUG -fomit-frame-pointer -s -std=gnu99 MAKEFLAGS += -j$(nproc) TARGETS=helloworld @@ -17,45 +17,51 @@ int main () { - int sockfd; - int gai_result; - int bind_result; - struct addrinfo *res; - struct addrinfo hints; - memset(&hints, 0, sizeof(hints)); + int sockfd; // socket fd + int gai_result; // result from getaddrinfo + int bind_result; // result from bind + struct addrinfo *res; // Pointer to linked list sent back by gai + struct addrinfo hints; // Options we pass to gai + memset(&hints, 0, sizeof(hints)); // We set this struct to 0 and then give it all the options we want below hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; - gai_result = getaddrinfo(NULL, "62000", &hints, &res); + gai_result = getaddrinfo(NULL, "62000", &hints, &res); // NULL because we are going to listen if (gai_result != 0) { fprintf(stderr, "gai_result: %d\n", gai_result); exit(1); } - sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol); + sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol); // Socket, get the family, socktype and protocol. if (sockfd == -1) { fprintf(stderr, "sockfd: %d\n", sockfd); exit(1); } - bind_result = bind(sockfd, res->ai_addr, res->ai_addrlen); + bind_result = bind(sockfd, res->ai_addr, res->ai_addrlen); // Bind to socket fd. pass our own address (ai_addr) and the length if (bind_result != 0) { fprintf(stderr, "bind_result: %d\n", bind_result); exit(1); } - listen(sockfd, BACKLOG); - socklen_t addr_size; - struct sockaddr_storage their_addr; - addr_size = sizeof(their_addr); - int newfd; - newfd = accept(sockfd, (struct sockaddr *)&their_addr, &addr_size); + freeaddrinfo(res); // free the info because we dont need it anymore + + fprintf(stdout, "Waiting for a connection...\n"); + listen(sockfd, BACKLOG); // Actually listen for connections with the sockfd + + socklen_t addr_size; // Size of address + struct sockaddr_storage their_addr; // pass this struct to accept because it will hold their address + addr_size = sizeof(their_addr); // Check the size of their addr + int newfd; // New fd + newfd = accept(sockfd, (struct sockaddr *)&their_addr, &addr_size); // Actually accept. Pass the sockfd, cast their_addr to sockaddr and send the address to the function. Pass the addr_size address so we can handle the length. + fprintf(stdout, "Connection is being established...\n"); if (newfd == -1) { fprintf(stderr, "newfd: %d\n", newfd); exit(1); } + fprintf(stdout, "Connection established!\n"); char *msg = "Server says hi!\n"; int len; int bytes_sent; |