1+ #include " ../src/netlib.hpp"
2+ #include < csignal>
3+ #include < iomanip>
4+ #include < iostream>
5+
6+ using namespace std ::chrono_literals;
7+
8+ void exit_handler (int s){
9+ std::cout << " Goodbye!" << std::endl;
10+ exit (EXIT_SUCCESS );
11+ }
12+
13+ int main (int argc, char ** argv) {
14+
15+ signal (SIGINT , exit_handler);
16+ uint16_t port = 37 ;
17+ std::string time_host = " time.nist.gov" ; // https://tf.nist.gov/tf-cgi/servers.cgi#
18+ if (argc == 3 ) {
19+ time_host = argv[1 ];
20+ port = std::atol (argv[2 ]);
21+ }
22+
23+ std::cout << " Connecting to " << time_host << " on port " << port << std::endl;
24+ netlib::client client;
25+
26+ std::error_condition client_create_res =
27+ client.connect (time_host, port, netlib::AddressFamily::IPv4,
28+ netlib::AddressProtocol::UDP , 1000ms);
29+
30+ if (client_create_res) {
31+ std::cerr << " Error connecting to host, error : " << client_create_res.message () << std::endl;
32+ exit (EXIT_FAILURE );
33+ }
34+
35+ // since time uses udp, we need to send some random udp datagram to server,
36+ // since it has no way of knowing that we want the datetime
37+ // (udp is connectionless)
38+ // Interesting that the send payload can be lower than the 4 expected bytes -
39+ // this could potentially be used in an udp reflection attack
40+ std::vector<uint8_t > dummy_payload (4 , 0 );
41+ auto send_res = client.send (dummy_payload, 1000ms);
42+ if (send_res.second ) {
43+ std::cout << " Error sending byte in udp mode for triggering response: " <<
44+ send_res.second .message () << std::endl;
45+ exit (EXIT_FAILURE );
46+ }
47+
48+ auto time_res = client.recv (1024 , 1000ms);
49+ if (time_res.second ) {
50+ std::cerr << " Failed to get UDP datagram. Error: " << time_res.second .message () << std::endl;
51+ exit (EXIT_FAILURE );
52+ }
53+
54+ if (time_res.first .size () != 4 ) {
55+ std::cerr << " Did not recieve 32 bits - instead got " << time_res.first .size () << std::endl;
56+ exit (EXIT_FAILURE );
57+ }
58+
59+ uint32_t time_result = (time_res.first [0 ] << 24 ) |
60+ (time_res.first [1 ] << 16 ) |
61+ (time_res.first [2 ] << 8 ) |
62+ (time_res.first [3 ]);
63+
64+ std::cout << " Value from server: " << time_result << std::endl;
65+ // print out actual time
66+ std::time_t temp = time_result - 2208988800 ;
67+ std::cout << std::put_time (std::gmtime (&temp), " Formatted: %Y-%m-%d %I:%M:%S %p" ) << std::endl;
68+ }
0 commit comments