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

#define CLIENT_PORT 11592
#define COMMAND_LENGTH 25
#define CLIENT_IP "192.168.56.104" 

int main() {
    int sockfd;
    struct sockaddr_in server_addr, client_addr;
    char buf[256];
    socklen_t len = sizeof(client_addr);

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0) {
        perror("socket creation failed");
        exit(EXIT_FAILURE);
    }

    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(CLIENT_PORT);
    server_addr.sin_addr.s_addr = INADDR_ANY;

    if (bind(sockfd, (const struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }

    
    memset(&client_addr, 0, sizeof(client_addr));
    client_addr.sin_family = AF_INET;
    client_addr.sin_port = htons(CLIENT_PORT);
    client_addr.sin_addr.s_addr = inet_addr(CLIENT_IP);
    sendto(sockfd, "HELLO:", 6, 0, (struct sockaddr*)&client_addr, sizeof(client_addr));

    while (1) {
        int n = recvfrom(sockfd, buf, 256, 0, (struct sockaddr*)&client_addr, &len);
        buf[n] = '\0';

        if (strncmp(buf, "CMD:", 4) == 0) {
            char response[256];
            sprintf(response, "RESP:%d:%s", (rand() % 1000) + 1, buf + 4); // +4, by pominąć "CMD:"
	    puts(response);
            sendto(sockfd, response, strlen(response), 0, (struct sockaddr*)&client_addr, len);
        }
    }

    return 0;
}
