added sparse test
[tridge/junkcode.git] / rtime2.c
1 #define _GNU_SOURCE
2
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <string.h>
6 #include <time.h>
7 #include <errno.h>
8 #include <sys/socket.h>
9 #include <netdb.h>
10 #include <unistd.h>
11 #include <stdlib.h>
12 #include <fcntl.h>
13 #include <sys/types.h>
14 #include <sys/time.h>
15 #include <arpa/inet.h>
16 #include <netinet/in.h>
17
18 /* open a socket to a tcp remote host with the specified port */
19 static int open_socket_out(const char *host, int port)
20 {
21         struct sockaddr_in sock_out;
22         int res;
23         struct hostent *hp;  
24         struct in_addr addr;
25
26         res = socket(PF_INET, SOCK_STREAM, 0);
27         if (res == -1) {
28                 return -1;
29         }
30
31         inet_aton(host, &addr);
32
33         sock_out.sin_addr = addr;
34         sock_out.sin_port = htons(port);
35         sock_out.sin_family = PF_INET;
36
37         if (connect(res,(struct sockaddr *)&sock_out,sizeof(sock_out)) != 0) {
38                 close(res);
39                 fprintf(stderr,"failed to connect to %s (%s)\n", 
40                         host, strerror(errno));
41                 return -1;
42         }
43
44         return res;
45 }
46
47
48 static void unix_time(time_t t)
49 {
50         struct tm *tm;
51
52         tm = gmtime(&t);
53         
54         printf("%04d%02d%02d%02d%02d%02d\n",
55                tm->tm_year + 1900, tm->tm_mon+1, tm->tm_mday, tm->tm_hour, 
56                tm->tm_min, tm->tm_sec);
57 }
58
59 int main(int argc, char *argv[])
60 {
61         int sock;
62         unsigned t, ofs;
63         char *host;
64
65         if (argc != 3) {
66                 printf("rtime <server> <offset>\n");
67                 exit(1);
68         }
69
70         host = argv[1];
71         ofs = atoi(argv[2]);
72
73         sock = open_socket_out(argv[1], 37);
74
75         if (read(sock, &t, sizeof(t)) == 4) {
76                 unix_time(ofs + ntohl(t) - 2208988800U);
77                 return 0;
78         }
79         return -1;
80 }