#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <errno.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <inttypes.h>
#include <math.h>
#include <time.h>
#define _POSIX_C_SOURCE 200809L
#define MAX_BUF 128

int print_ms()
{
    long ms;
    time_t s;
    struct timespec spec;

    clock_gettime(CLOCK_REALTIME, &spec);

    s  = spec.tv_sec;
    ms = round(spec.tv_nsec / 1.0e6);
    if (ms > 999) {
        s++;
        ms = 0;
    }
    return ms;
}

int main(){

    int s;
    unsigned char mip_str[INET_ADDRSTRLEN];
    struct addrinfo h, *r;

    memset(&h, 0, sizeof(struct addrinfo));
    h.ai_family=AF_INET;
    h.ai_socktype=SOCK_STREAM;

    if(getaddrinfo("192.168.56.102", "11630", &h, &r)!=0) {
        printf("[%d ms] ERROR: %s\n", print_ms(), strerror(errno));
        exit(-1);
    }

    if((s=socket(r->ai_family, r->ai_socktype, r->ai_protocol))==-1) {
        printf("[%d ms] ERROR: %s\n", print_ms(), strerror(errno));
        exit(-1);
    }
    if(connect(s, r->ai_addr, r->ai_addrlen)!=0) {
        printf("[%d ms] ERROR: %s\n", print_ms(), strerror(errno));
        exit(-1);
    }

    ssize_t bytes_sent;
    char my_hello[MAX_BUF];

    for(;;){
        int number = print_ms();
        char ch[100];
        time_t t;
        time(&t);
        sprintf(ch, "%s%s%d", ctime(&t), "ms:", number);
        snprintf(my_hello, MAX_BUF, ch); 

        bytes_sent = send(s, my_hello, strlen(my_hello), MSG_NOSIGNAL);

        if(bytes_sent < 0){
            printf("[%d ms] ERROR: Failed to send message: '%s'\n", print_ms(), strerror(errno));
            close(s);
            break;
        } else {
            printf("[%d ms] Sent message (%zd bytes): %s\n", print_ms(), bytes_sent, my_hello);
        }

        usleep(850000);
    }

    freeaddrinfo(r);
    close(s);
    return 0;
}
