98 lines
2.3 KiB
C
98 lines
2.3 KiB
C
#include <arpa/inet.h>
|
|
#include <netinet/in.h>
|
|
#include <stdio.h>
|
|
#include <sys/types.h>
|
|
#include <sys/socket.h>
|
|
#include <unistd.h>
|
|
#include <pthread.h>
|
|
#include <sys/time.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
|
|
#define BUFLEN sizeof(struct timeval)
|
|
#define PORT 9876
|
|
|
|
static int sock_fd, slen;
|
|
|
|
void diep(char * s)
|
|
{
|
|
perror(s);
|
|
exit(1);
|
|
}
|
|
|
|
static long long time_diff(struct timeval * one, struct timeval * two)
|
|
{
|
|
long long t1 = ((long long) one->tv_sec) * 1000000
|
|
+ (long long) one->tv_usec;
|
|
long long t2 = ((long long) two->tv_sec) * 1000000
|
|
+ (long long) two->tv_usec;
|
|
return t1 - t2;
|
|
}
|
|
|
|
void * thread(void * arg)
|
|
{
|
|
struct sockaddr_in si_other;
|
|
char time_str[100];
|
|
struct timeval tv_msg, tv_now, tv_last;
|
|
for (;;)
|
|
{
|
|
if (recvfrom(sock_fd, &tv_msg, BUFLEN, 0,
|
|
(struct sockaddr *) &si_other, &slen) == -1)
|
|
diep("recvfrom()");
|
|
gettimeofday(&tv_now, NULL);
|
|
struct tm * lt = localtime(&tv_now.tv_sec);
|
|
strftime(time_str, 100, "%F %T", lt);
|
|
printf("Rcv: %s, rtt: %lld, elapsed: %lld\n",
|
|
time_str,
|
|
time_diff(&tv_now, &tv_msg),
|
|
time_diff(&tv_now, &tv_last));
|
|
tv_last.tv_sec = tv_now.tv_sec;
|
|
tv_last.tv_usec = tv_now.tv_usec;
|
|
}
|
|
}
|
|
|
|
int main(int argc, char * argv[])
|
|
{
|
|
int interval;
|
|
struct timeval tv;
|
|
struct sockaddr_in si_other;
|
|
if (argc != 3)
|
|
{
|
|
printf("Usage: client server-address msec-interval\n");
|
|
exit(2);
|
|
}
|
|
interval = atoi(argv[2]) * 1000;
|
|
|
|
slen = sizeof(si_other);
|
|
|
|
if ((sock_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
|
|
diep("socket");
|
|
|
|
memset((char *) &si_other, 0, sizeof(si_other));
|
|
si_other.sin_family = AF_INET;
|
|
si_other.sin_port = htons(PORT);
|
|
inet_aton(argv[1], &si_other.sin_addr);
|
|
#if 0
|
|
if (bind(sock_fd, (struct sockaddr *) &si_other, sizeof(si_other)) == -1)
|
|
diep("bind");
|
|
#endif
|
|
|
|
pthread_t t;
|
|
if (pthread_create(&t, NULL, thread, NULL) != 0)
|
|
diep("pthread_create()");
|
|
|
|
usleep(100000);
|
|
for (;;)
|
|
{
|
|
gettimeofday(&tv, NULL);
|
|
if (sendto(sock_fd, &tv, BUFLEN, 0,
|
|
(struct sockaddr *) &si_other, slen) == -1)
|
|
diep("sendto()");
|
|
usleep(interval);
|
|
}
|
|
|
|
close(sock_fd);
|
|
return 0;
|
|
}
|
|
|