ntp實(shí)現(xiàn)原理
我們看一下為啥說(shuō)ntp從實(shí)現(xiàn)時(shí)間同步的角度來(lái)說(shuō)是很簡(jiǎn)單的。在pc上,以windows為例,手動(dòng)關(guān)閉打開(kāi)一下自動(dòng)更新時(shí)間,會(huì)觸發(fā)一次ntp時(shí)間同步。
這個(gè)時(shí)候,我們可以拿到ntp完整的request/response報(bào)文,如下:
ntp client request:
ntp server response:
如上圖,我們可以看到,我們可以拿到同步原理提到的t1, t2, t3;而t4是client接收到server response時(shí)的時(shí)間,那么上述時(shí)間分別是如何來(lái)的呢。
* t1: client發(fā)送request的前一刻,記下當(dāng)前utc時(shí)間,然后塞入到request transmit timestamp中去。但是這個(gè)不能作為真正的t1來(lái)使用,因?yàn)榍懊嫣岬搅?,ntp是使用的udp,所以有可能會(huì)丟包。因此真正的t1應(yīng)該ntp server收到client request時(shí),從request報(bào)文中提取到t1,最后再給到client使用。也就是上圖的t1。
* t2: 也就是server收到client request的時(shí)間
* t3: server發(fā)送response的時(shí)間
* t4: client收到server response的時(shí)間
知道這些原理之后,我們就可以很好設(shè)計(jì)出我們的代碼實(shí)現(xiàn)思路,如下:
C++
//ntp client
// send request with t1
std::chrono::time_point_cast(
std::chrono::system_clock::now());
std::time_t time_stamp = time_point.time_since_epoch().count();
request_message_- >SetTransTs(time_stamp);
int ret = SendMsg(request_message_- >GetData(), MESSAGE_LENGTH);
// receive response, and get t1, t2, t3
int ret = RecvMsg(request_message_- >GetData(), MESSAGE_LENGTH);
auto req_tx_ts_ = response_message_- >GetOriginTs(); // t1
auto req_rx_ts_ = response_message_- >GetRecvTs(); // t2
auto resp_tx_ts_ = response_message_- >GetTransTs(); // t3
auto time_point = std::chrono::time_point_cast(
std::chrono::system_clock::now());
std::time_t time_stamp = time_point.time_since_epoch().count();
auto resp_rx_ts_us_ = static_cast(time_stamp); // t4
auto offset =
req_rx_ts_us_ - req_tx_ts_us_ + resp_tx_ts_us_ - resp_rx_ts_us_;
offset /= 2;
// adjust the clock
AdjustClock(offset);
C++
// ntp server
// receive ntp request message
RecvMsg(request_message_- >GetData(), MESSAGE_LENGTH);
// get receive request_frame timestamp, get t1, t2
auto time_point = std::chrono::time_point_cast(
std::chrono::system_clock::now());
auto req_rx_ts = time_point.time_since_epoch().count();//t2
auto req_tx_ts = request_message_- >GetTransTs();//t1
// send ntp response message
response_message_- >SetOriginTs(req_tx_ts);//t1
response_message_- >SetRecvTs(req_rx_ts);//t2
auto time_point = std::chrono::time_point_cast(
std::chrono::system_clock::now());
auto resp_tx_ts = time_point.time_since_epoch().count();
response_message_- >SetTransTs(resp_tx_ts);//t3
SendMsg(response_message_- >GetData(), MESSAGE_LENGTH);
-
車(chē)載
+關(guān)注
關(guān)注
18文章
615瀏覽量
83413 -
時(shí)間同步
+關(guān)注
關(guān)注
1文章
122瀏覽量
10019 -
時(shí)鐘同步
+關(guān)注
關(guān)注
0文章
89瀏覽量
12788 -
NTP
+關(guān)注
關(guān)注
1文章
176瀏覽量
13938
發(fā)布評(píng)論請(qǐng)先 登錄
相關(guān)推薦
評(píng)論