socket.c 1.94 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
/*
 * Creator: Naman Dixit
 * Notice: © Copyright 2020 Naman Dixit
 */

typedef enum Socket_Kind {
    Socket_Kind_NONE,
    Socket_Kind_INTERNAL,
    Socket_Kind_EXTERNAL,
} Socket_Kind;

internal_function
Sint socketCreateListener (Char *port)
{
    printf("Openiing socket on port %s\n", port);

    // NOTE(naman): Create a socket for IPv4 and TCP.
    Sint sock_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (sock_fd < 0) {
        perror("ERROR opening socket");
        exit(-1);
    }

    // NOTE(naman): This helps avoid spurious EADDRINUSE when the previous instance of this
    // server died.
    int opt = 1;
    if (setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0) {
        perror("setsockopt");
        exit(-1);
    }

    // NOTE(naman): Get actual internet address to bind to using IPv4 and TCP,
    // and listening passively
    struct addrinfo hints = {.ai_family = AF_INET,
                             .ai_socktype = SOCK_STREAM,
                             .ai_flags = AI_PASSIVE};
    struct addrinfo *addrinfo = NULL;
    Sint s = getaddrinfo(NULL, port, &hints, &addrinfo);
    if (s != 0) {
        fprintf(stderr, "Error: getaddrinfo: %s\n", gai_strerror(s));
        exit(-1);
    }

    // NOTE(naman): Assign an address to the socket
    if (bind(sock_fd, addrinfo->ai_addr, addrinfo->ai_addrlen) != 0) {
        perror("bind()");
        exit(-1);
    }

    // NOTE(naman): Start listening for incoming connections
    if (listen(sock_fd, MAX_SOCKET_CONNECTIONS_REQUEST) != 0) {
        perror("listen()");
        exit(-1);
    }

    // NOTE(naman): Set the socket as non-blocking
    int flags = fcntl(sock_fd, F_GETFL, 0);
    if (flags == -1) {
        perror("fcntl F_GETFL");
        exit(-1);
    }
    if (fcntl(sock_fd, F_SETFL, flags | O_NONBLOCK) == -1) {
        perror("fcntl F_SETFL O_NONBLOCK");
        exit(-1);
    }

    printf("Log: Waiting for connection on port %s...\n", port);

    return sock_fd;
}