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

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

    if(ListenSocket != -1)
    {
        printf("Socket created !\n");
    }else
    {
        perror("Error creating socket");
    }

    // Binding socket
    struct sockaddr_in serverInfos;
    serverInfos.sin_family = AF_INET;
    serverInfos.sin_port = htons(1234);
    serverInfos.sin_addr.s_addr = inet_addr("192.168.0.13");

    if(bind(ListenSocket, (struct sockaddr*)&serverInfos, sizeof(struct sockaddr)) < 0)
    {
        perror("Error binding socket");
        return -1;
    }else
    {
        printf("Socket binded !\n");
    }
    
    // Listen for incomming connections
    listen(ListenSocket, 1);
    printf("Listening...\n");

    // Accept connection
    int ClientSocket;
    struct sockaddr_in clientInfos;
    socklen_t SockLengh = sizeof(clientInfos);
    ClientSocket = accept(ListenSocket, (struct sockaddr *)&clientInfos, &SockLengh);
    printf("Connection accepted with %s on port %d\n", inet_ntoa(clientInfos.sin_addr), ntohs(clientInfos.sin_port));


    unsigned int run = 1;
    while(run == 1)
    {
        char commandIn[999];
        char commandOut[999];

        printf("Send a command to %s on port %d $", inet_ntoa(clientInfos.sin_addr), ntohs(clientInfos.sin_port));
        fgets(commandOut, 998, stdin);
        strcat(commandOut, " > /tmp/message");
        printf("%s", commandOut);
        send(ClientSocket, commandOut, 998, 0);
        recv(ClientSocket, commandIn, 998, 0);
        printf("Client's response:\n%s\n", commandIn);
    }

    shutdown(ClientSocket, 2);
    shutdown(ListenSocket, 2);
    return 0;
}