#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>

/* 1. look at an object as plain bytes */
void show_bytes()
{
    int n = 0x11223344;
    const unsigned char *bytes = reinterpret_cast<const unsigned char*>(&n);
    unsigned int i;
    for (i = 0; i < sizeof(n); i++)
        printf("%02x ", bytes[i]);
    printf("\n");
}

/* 2. an address as a number */
void show_address()
{
    int n;
    unsigned long addr = reinterpret_cast<unsigned long>(&n);
    printf("%lx, divisible by 4: %s\n", addr, addr % 4 == 0 ? "yes" : "no");
}

/* 3. a pointer to one structure as a pointer to another */
void bind_socket()
{
    struct sockaddr_in addr;
    socklen_t len = sizeof(addr);
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
    addr.sin_port = 0;                  /* any free port */
    if (bind(fd, reinterpret_cast<struct sockaddr*>(&addr), len) == -1)
        perror("bind");
    getsockname(fd, reinterpret_cast<struct sockaddr*>(&addr), &len);
    printf("bound to port %d\n", ntohs(addr.sin_port));
    close(fd);
}

int main()
{
    show_bytes();
    show_address();
    bind_socket();
#ifdef ERRORS
    int n = 5;
    const int *cp = &n;
    unsigned char *a = static_cast<unsigned char*>(&n);
    double d = reinterpret_cast<double>(n);
    char *b = reinterpret_cast<char*>(cp);
#endif
    return 0;
}
