#include <unistd.h>
#include <fcntl.h>
#include <sys/socket.h>
+#include <time.h>
#include "sock_util.h"
+#include "utils.h"
#define DEFAULT_SERVER_LISTEN_PORT 43210
#define SERVER_BACKLOG 5
#define DATA_SIZE 120
+#define PACKET_INDEX_SIZE sizeof(unsigned long long)
+#define PACKET_TIMESPEC_SIZE sizeof(time_t)
+
static char data[DATA_SIZE];
-static int receive_buffer(int sockfd)
+static ssize_t receive_buffer(int sockfd)
{
return recv(sockfd, data, DATA_SIZE, 0);
}
printf("data: %s\n\n", data);
}
+static void print_buffer_meta(void)
+{
+ unsigned long long index;
+ time_t curr_time_secs;
+ time_t sender_time_secs;
+ char *ptr;
+
+ curr_time_secs = time(NULL);
+
+ ptr = data + DATA_SIZE;
+ index = * (unsigned long long *) ptr;
+ ptr += PACKET_INDEX_SIZE;
+ sender_time_secs = * (time_t *) ptr;
+
+ printf("received packet index %llu, ", index);
+ if (sender_time_secs > curr_time_secs)
+ printf("negative latency (weird)\n");
+ else
+ printf("latency %lu seconds\n",
+ curr_time_secs - sender_time_secs);
+}
+
+static void handle_data(int sockfd)
+{
+ ssize_t nbytes;
+
+ nbytes = receive_buffer(sockfd);
+ DIE(nbytes < 0, "receive_buffer");
+ print_buffer_meta();
+}
+
int main(void)
{
int listenfd;
listenfd = tcp_listen_connections(DEFAULT_SERVER_LISTEN_PORT,
SERVER_BACKLOG);
- if (listenfd < 0) {
- exit(EXIT_FAILURE);
- }
+ DIE(listenfd < 0, "tcp_listen_connections");
sockfd = accept(listenfd, (SSA *) &addr, &addrlen);
- if (sockfd < 0) {
- perror("sockfd");
- exit(EXIT_FAILURE);
- }
+ DIE(sockfd < 0, "accept");
- if (receive_buffer(sockfd) < 0) {
- perror("readv");
- exit(EXIT_FAILURE);
+ while (1) {
+ handle_data(sockfd);
}
- printf("\n-- data received!\n\n");
- print_buffer();
close(sockfd);
close(listenfd);