#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int main(int argc, char **argv)
{
    char buffer[1024];
    char *clientIP;
    int connection, port = 7001;
    int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    socklen_t clientlen;
    sockaddr_in serverAddr, clientAddr;
    // Server
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(port);
    serverAddr.sin_addr.s_addr = INADDR_ANY;
    clientlen = sizeof(clientAddr);
    if(-1 == bind(sock,(struct sockaddr *)&serverAddr, sizeof(serverAddr)))
    {
        perror("error bind failed");
        close(sock);
        exit(EXIT_FAILURE);
    }
    if(-1 == listen(sock, 10))
    {
        perror("listen failed");
        close(sock);
        exit(EXIT_FAILURE);
    }
    printf("Listening on port %i...\n", port);
    for(;;)
    {
        connection = accept(sock, (struct sockaddr *)&clientAddr, &clientlen);
        if(0 > connection)
        {
            perror("accept failed");
            close(sock);
            exit(EXIT_FAILURE);
        }
        clientIP = inet_ntoa(clientAddr.sin_addr);
        printf("Connection established!\n");
        sprintf(buffer, "HTTP/1.1 200 OK\r\n\
Content-Type: text/html; charset=utf8\r\n\
\r\n\
<html><head><title>Algorithmen und Datenstrukturen</title></head>\r\n\
<body><h1>Algorithmen und Datenstrukturen</h1>\r\n\
<h2>HTTP</h2>\r\n\
<p>Your IP is %s</p></body></html>\r\n\r\n", clientIP);
        send(connection, buffer, strlen(buffer), 0);
        shutdown(connection, SHUT_RDWR);
        close(connection);
    }
    close(sock);
    return(0);
}

