/* =============================================================================
 * 02_addresses.c -- IP addresses, byte order, and turning a name into an address
 * =============================================================================
 *
 * [Idea]
 *   Before a program can connect to anything it must answer: "what is the
 *   address?" Three layers sit between a human name and the bytes the kernel
 *   needs:
 *     1. a NAME            "www.cmu.edu"      (what people type)
 *     2. an IP ADDRESS     128.2.42.52        (what routers forward on)
 *     3. a sockaddr struct bytes in a fixed layout, in NETWORK byte order
 *   getaddrinfo() does 1 -> 3 in one call. This demo shows each layer, and the
 *   byte-order trap that sits underneath all of them.
 *
 * [What it answers]
 *   - Why must a port number be converted with htons() before use?
 *   - What is "dotted decimal", really? (a human rendering of 32 bits)
 *   - What does getaddrinfo() return, and why is it a LIST?
 *
 * [Systems link]
 *   Lecture 2 showed this machine is little-endian. The Internet standardized
 *   on BIG-endian ("network byte order"), so every multi-byte field in every
 *   header must be converted. The demo dumps the actual bytes so you can see
 *   the swap rather than take it on faith.
 *
 * Build & run:    make run
 *                 ./build/02_addresses              (resolves localhost only)
 *                 ./build/02_addresses www.cmu.edu  (a real DNS lookup)
 *
 * `make run` deliberately resolves only "localhost", so the demo needs no
 * network and prints the same thing every time. Pass a hostname to see DNS.
 * -----------------------------------------------------------------------------
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>          /* getaddrinfo, getnameinfo, gai_strerror */
#include <sys/socket.h>
#include <netinet/in.h>     /* struct sockaddr_in, htons, htonl */
#include <arpa/inet.h>      /* inet_pton, inet_ntop */

/* Print the raw bytes of a value, so byte order is visible rather than claimed. */
static void dump_bytes(const char *label, const void *p, size_t n)
{
    const unsigned char *b = p;
    printf("    %-28s", label);
    for (size_t i = 0; i < n; i++)
        printf("%02x ", b[i]);
    printf("\n");
}

int main(int argc, char **argv)
{
    /* ---- 1. host byte order vs network byte order ------------------------ */
    printf("== 1. byte order: the Internet is big-endian, this CPU is not ==\n");

    uint16_t port_host = 8080;              /* 0x1F90 */
    uint16_t port_net  = htons(port_host);  /* "host to network, short" */
    printf("  port %u = 0x%04x\n", port_host, port_host);
    dump_bytes("in memory (host order):", &port_host, sizeof(port_host));
    dump_bytes("after htons (network):", &port_net, sizeof(port_net));

    uint32_t ip_host = 0x80022A34;          /* 128.2.42.52 as a 32-bit number */
    uint32_t ip_net  = htonl(ip_host);
    printf("  address 0x%08x\n", ip_host);
    dump_bytes("in memory (host order):", &ip_host, sizeof(ip_host));
    dump_bytes("after htonl (network):", &ip_net, sizeof(ip_net));
    printf("  => the bytes are REVERSED. ntohs/ntohl convert back. Forgetting\n");
    printf("     the conversion is the classic 'connects to port 36895' bug\n");
    printf("     (0x1F90 byte-swapped is 0x901F = 36895).\n");

    /* ---- 2. dotted decimal is just a rendering of 32 bits ---------------- */
    printf("\n== 2. dotted decimal <-> 32 bits (inet_pton / inet_ntop) ==\n");
    const char *dotted = "128.2.42.52";
    struct in_addr addr;
    if (inet_pton(AF_INET, dotted, &addr) != 1) {
        fprintf(stderr, "inet_pton failed\n"); return 1;
    }
    printf("  inet_pton(\"%s\") -> 0x%08x (network order in memory)\n",
           dotted, ntohl(addr.s_addr));
    dump_bytes("the four bytes:", &addr, sizeof(addr));
    char back[INET_ADDRSTRLEN];
    inet_ntop(AF_INET, &addr, back, sizeof(back));
    printf("  inet_ntop back -> \"%s\"  (round trip ok: %s)\n",
           back, strcmp(back, dotted) == 0 ? "yes" : "NO");
    printf("  => each dotted number is ONE BYTE: 128.2.42.52 = 80 02 2a 34\n");

    /* ---- 3. the socket address structure --------------------------------- */
    printf("\n== 3. struct sockaddr_in: what connect()/bind() actually take ==\n");
    struct sockaddr_in sa;
    memset(&sa, 0, sizeof(sa));             /* [C tip] always zero it first */
    sa.sin_family = AF_INET;                /* address family: IPv4          */
    sa.sin_port   = htons(80);              /* port, NETWORK order           */
    sa.sin_addr   = addr;                   /* address, NETWORK order        */
    printf("  sizeof(struct sockaddr_in)  = %zu bytes\n", sizeof(sa));
    printf("  sizeof(struct sockaddr_in6) = %zu bytes (IPv6 is bigger)\n",
           sizeof(struct sockaddr_in6));
    printf("  sin_family=%d  sin_port=0x%04x (= %u via ntohs)\n",
           sa.sin_family, sa.sin_port, ntohs(sa.sin_port));
    dump_bytes("the whole struct:", &sa, sizeof(sa));
    /* [Edge cases] The raw dump is platform-specific at the very front. On
       macOS/BSD the struct begins with a 1-byte sin_len then a 1-byte
       sin_family, so the first two bytes read "00 02". On Linux there is no
       sin_len and sin_family is a 2-byte field, so they read "02 00". Both are
       16 bytes total and both work through the API -- which is the argument for
       never hand-building these bytes and letting getaddrinfo do it (step 4). */
    printf("  (the first bytes are platform-specific: macOS/BSD has a sin_len\n");
    printf("   byte before sin_family, so \"00 02\"; Linux has a 2-byte family,\n");
    printf("   so \"02 00\". Both are 16 bytes and both work via the API.)\n");
    printf("  => the generic 'struct sockaddr *' in the socket API is a cast\n");
    printf("     target; the real struct is the family-specific one.\n");

    /* ---- 4. name -> address, the modern way ----------------------------- */
    const char *host = (argc > 1) ? argv[1] : "localhost";
    printf("\n== 4. getaddrinfo(\"%s\", \"80\") ==\n", host);

    struct addrinfo hints, *res, *p;
    memset(&hints, 0, sizeof(hints));
    hints.ai_socktype = SOCK_STREAM;    /* we want TCP, not UDP, entries     */
    hints.ai_family   = AF_UNSPEC;      /* accept both IPv4 and IPv6         */

    int rc = getaddrinfo(host, "80", &hints, &res);
    if (rc != 0) {
        /* Not a crash: a name that does not resolve is an ordinary outcome. */
        printf("  getaddrinfo failed: %s\n", gai_strerror(rc));
        printf("  (no DNS available? the default 'localhost' needs no network)\n");
        return 0;
    }

    int n = 0;
    for (p = res; p != NULL; p = p->ai_next) {
        char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
        /* NI_NUMERIC*: give me the numbers, do not reverse-resolve to a name */
        getnameinfo(p->ai_addr, p->ai_addrlen,
                    hbuf, sizeof(hbuf), sbuf, sizeof(sbuf),
                    NI_NUMERICHOST | NI_NUMERICSERV);
        printf("  [%d] family=%-5s addr=%-40s port=%s\n", n++,
               p->ai_family == AF_INET ? "IPv4" :
               p->ai_family == AF_INET6 ? "IPv6" : "other",
               hbuf, sbuf);
    }
    freeaddrinfo(res);                  /* [C tip] the list is malloc'd: free it */

    printf("  => %d address(es). getaddrinfo returns a LINKED LIST because a\n", n);
    printf("     name can have several addresses (IPv4 AND IPv6, or many hosts\n");
    printf("     behind one name). A correct client TRIES EACH until one\n");
    printf("     connects -- which is exactly what Lecture 20's client does.\n");

    printf("\nObservations\n------------\n");
    printf("- A port is two bytes and an IPv4 address is four; both travel in\n");
    printf("  BIG-endian network order, so on this little-endian CPU the bytes\n");
    printf("  in memory are reversed by htons/htonl (shown above, not asserted).\n");
    printf("- 'Dotted decimal' is a human rendering: 128.2.42.52 is the four\n");
    printf("  bytes 80 02 2a 34. inet_pton/inet_ntop convert both ways.\n");
    printf("- getaddrinfo() hides the whole mess (DNS, IPv4 vs IPv6, ports,\n");
    printf("  byte order) and hands back ready-made sockaddr structures. Its\n");
    printf("  result is a list, and the FIRST entry is not always the one that\n");
    printf("  works -- on this machine 'localhost' lists IPv6 ::1 before IPv4.\n");
    return 0;
}

/*
 * Observations (author's machine, Apple M4 Pro, macOS):
 *   port 8080 = 0x1f90 -> in memory "90 1f", after htons "1f 90"
 *   0x80022a34 -> in memory "34 2a 02 80", after htonl "80 02 2a 34"
 *   inet_pton("128.2.42.52") round-trips; the four bytes are 80 02 2a 34
 *   sizeof(sockaddr_in)=16, sizeof(sockaddr_in6)=28
 *   getaddrinfo("localhost","80") -> [0] IPv6 ::1, [1] IPv4 127.0.0.1
 *
 *   - The byte reversal is visible in the dumps: this CPU stores the low byte
 *     first, the network wants the high byte first.
 *   - localhost resolves to TWO addresses and IPv6 comes FIRST, which is why a
 *     client must walk the list instead of using res->ai_addr blindly.
 *   - Run with a hostname argument (e.g. www.cmu.edu) for a real DNS lookup;
 *     the default needs no network so `make run` stays reproducible.
 */
