ntp4 client, time_source interface
[quarnos.git] / services / ntp_client.h
blob9b2c4b508ff783593e9ff14ae5cb780cfab0ba3e
1 #ifndef _NTP_CLIENT_H_
2 #define _NTP_CLIENT_H_
4 #include "resources/net/client_socket.h"
5 #include "resources/net/udp.h"
7 #include "time_source.h"
9 namespace services {
10 class ntp_client : time_source {
11 private:
12 typedef int u64[2];
13 struct ntp_packet {
14 u8 flags;
15 u8 stratum;
16 u8 poll_int;
17 u8 precision;
18 u32 root_delay;
19 u32 root_dispersion;
20 u32 ref_clock_id;
21 u64 ref_clock_update;
22 u64 orig_time_stamp;
23 u64 rec_time_stamp;
24 u64 trans_time_stamp;
27 enum ntp_flags {
28 ntp_cli = 3,
29 ntp_srv = 4,
30 ntp_ver4 = 0x20,
31 ntp_alarm = 0xc0
34 enum {
35 ntp_port = 123
38 p<net::client_socket> client;
40 p<ntp_packet> pkg;
41 public:
42 ~ntp_client() {
43 if (client.valid())
44 client->close();
47 void set(p<net::udp> u) {
48 client = u->create_client();
49 client->connect(net::ipv4_addr::from_le(213 << 24 | 134 << 16 | 184 << 8 | 12), ntp_port);
51 pkg = new ntp_packet;
54 time_source::time_stamp get_timestamp() {
55 pkg->flags = ntp_cli | ntp_ver4 | ntp_alarm;
56 pkg->poll_int = 6;
57 pkg->ref_clock_id = to_be32(0x494e4954);
59 client->write(buffer::to_mem(pkg));
61 buffer buf = buffer::to_mem(pkg);
62 client->read(buf);
64 time_source::time_stamp timestamp = from_be32(buf.cast<ntp_packet>()->rec_time_stamp[0]);
66 /* NTP uses Jan 01 1900 as a base, we need Jan 01 1970 */
67 timestamp -= 2208988800;
69 return timestamp;
74 #endif