#include <stdio.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
    // Creating the first socket (for listening purpose)
    int ListenSocket;
    ListenSocket = socket(AF_INET, SOCK_STREAM, 0);// TCP socket

    if(ListenSocket != -1)// verifying that the socket is created succesfully
    {
        printf("Socket created !\n");
    }else
    {
        perror("Error creating socket");
        return 1;
    }

    // Binding socket
    struct sockaddr_in serverInfos;// the structure that store the server's infos (the computer that runs this server script) the structure type is "sockaddr_in" (google it if you want to know more about it)
    serverInfos.sin_family = AF_INET;// TCP method
    serverInfos.sin_port = htons(80);// PORT converted to a network format (chose the server's port)
    serverInfos.sin_addr.s_addr = inet_addr("192.168.0.13");// IP converted to a network format (chose the server's ip address, don't use 127.0.0.1)

    if(bind(ListenSocket, (struct sockaddr*)&serverInfos, sizeof(struct sockaddr)) < 0)// Binding the socket to the IP and the Port
    {
        perror("Error binding socket");
        return 1;
    }else
    {
        printf("Socket binded !\n");
    }
    
    // Listen for incomming connections
    listen(ListenSocket, 1);// Number of connections, i sat it to 1 but you can insert what you want
    printf("Listening...\n");// waiting for connections

    // Accept connection, at this point you can use threads/child processes
    int ClientSocket;
    struct sockaddr_in clientInfos;// this structure will store all the informations about the client connected to the 2nd socket (the client's dedicated socket)
    socklen_t SockLengh = sizeof(clientInfos);
    ClientSocket = accept(ListenSocket, (struct sockaddr *)&clientInfos, &SockLengh);// accepting connection and storing infos in the structure
    printf("Connection accepted with %s on port %d\n", inet_ntoa(clientInfos.sin_addr), ntohs(clientInfos.sin_port));// printing the client's IP and Port

    while(1)
    {
        // variables to store the data that you send/receive to/from the client
        char commandIn[999];
        char commandOut[999] = "Command received !";

        if(recv(ClientSocket, commandIn, 998, 0) != -1)// receive what the client sent you (if it did), if you get an infinite loop printing the client's data, replace "MSG_PEEK" by "0"
        {
            printf("Here is message from client: %s\n", commandIn);// printing client's data
            if(send(ClientSocket, commandOut, 998, 0) != -1)// sending to the client that we received his message (or data)
            {
                printf("Return sent !\n");
                return 0;
            }
        }
    }


    return 0;
}
