NTP 协议获取网络时间

从github 中找到的一份代码进行的修改
板卡是0区,手动加了8个时区

#include <iostream>
#include <netdb.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#define NTP_TIMESTAMP_DELTA 2208988800ull#define LI(packet)                                                             \(uint8_t)((packet.li_vn_mode & 0xC0) >> 6) // (li   & 11 000 000) >> 6
#define VN(packet)                                                             \(uint8_t)((packet.li_vn_mode & 0x38) >> 3) // (vn   & 00 111 000) >> 3
#define MODE(packet)                                                           \(uint8_t)((packet.li_vn_mode & 0x07) >> 0) // (mode & 00 000 111) >> 0void error(const char *msg) {perror(msg); // Print the error message to stderr.exit(0);     // Quit the process.
}int main(int argc, char *argv[]) {if (argc != 2) {printf("%s [ ntp server]\n", argv[0]);return 0;}int sockfd, n; // Socket file descriptor and the n return result from// writing/reading from the socket.int portno = 123; // NTP UDP port number.const char *host_name = argv[1]; // NTP server host-name.std::cout << "NTP: " << host_name << std::endl;// Structure that defines the 48 byte NTP packet protocol.typedef struct {uint8_t li_vn_mode; // Eight bits. li, vn, and mode.// li.   Two bits.   Leap indicator.// vn.   Three bits. Version number of the protocol.// mode. Three bits. Client will pick mode 3 for client.uint8_t stratum; // Eight bits. Stratum level of the local clock.uint8_t poll; // Eight bits. Maximum interval between successive messages.uint8_t precision; // Eight bits. Precision of the local clock.uint32_t rootDelay; // 32 bits. Total round trip delay time.uint32_trootDispersion; // 32 bits. Max error aloud from primary clock source.uint32_t refId;     // 32 bits. Reference clock identifier.uint32_t refTm_s; // 32 bits. Reference time-stamp seconds.uint32_t refTm_f; // 32 bits. Reference time-stamp fraction of a second.uint32_t origTm_s; // 32 bits. Originate time-stamp seconds.uint32_t origTm_f; // 32 bits. Originate time-stamp fraction of a second.uint32_t rxTm_s; // 32 bits. Received time-stamp seconds.uint32_t rxTm_f; // 32 bits. Received time-stamp fraction of a second.uint32_t txTm_s; // 32 bits and the most important field the client cares// about. Transmit time-stamp seconds.uint32_t txTm_f; // 32 bits. Transmit time-stamp fraction of a second.} ntp_packet; // Total: 384 bits or 48 bytes.// Create and zero out the packet. All 48 bytes worth.ntp_packet packet = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};memset(&packet, 0, sizeof(ntp_packet));// Set the first byte's bits to 00,011,011 for li = 0, vn = 3, and mode = 3.// The rest will be left set to zero.*((char *)&packet + 0) =0x1b; // Represents 27 in base 10 or 00011011 in base 2.// Create a UDP socket, convert the host-name to an IP address, set the port// number, connect to the server, send the packet, and then read in the return// packet.struct sockaddr_in serv_addr; // Server address data structure.struct hostent *server;       // Server data structure.sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); // Create a UDP socket.if (sockfd < 0)error("ERROR opening socket");server = gethostbyname(host_name); // Convert URL to IP.if (server == NULL)error("ERROR, no such host");// Zero out the server address structure.bzero((char *)&serv_addr, sizeof(serv_addr));serv_addr.sin_family = AF_INET;// Copy the server's IP address to the server address structure.bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr,server->h_length);// Convert the port number integer to network big-endian style and save it to// the server address structure.serv_addr.sin_port = htons(portno);// Call up the server using its IP address and port number.if (connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)error("ERROR connecting");// Send it the NTP packet it wants. If n == -1, it failed.n = write(sockfd, (char *)&packet, sizeof(ntp_packet));if (n < 0)error("ERROR writing to socket");// Wait and receive the packet back from the server. If n == -1, it failed.n = read(sockfd, (char *)&packet, sizeof(ntp_packet));if (n < 0)error("ERROR reading from socket");// These two fields contain the time-stamp seconds as the packet left the NTP// server. The number of seconds correspond to the seconds passed since 1900.// ntohl() converts the bit/byte order from the network's to host's// "endianness".packet.txTm_s = ntohl(packet.txTm_s); // Time-stamp seconds.packet.txTm_f = ntohl(packet.txTm_f); // Time-stamp fraction of a second.// Extract the 32 bits that represent the time-stamp seconds (since NTP epoch)// from when the packet left the server. Subtract 70 years worth of seconds// from the seconds since 1900. This leaves the seconds since the UNIX epoch// of 1970.// (1900)------------------(1970)**************************************(Time// Packet Left the Server)time_t txTm = (time_t)(packet.txTm_s - NTP_TIMESTAMP_DELTA);// Print the time we got from the server, accounting for local timezone and// conversion from UTC time.struct timeval tv = {tv.tv_sec = txTm + 8 * 3600};settimeofday(&tv, NULL);txTm+=8*3600;std::cout << "date:" << ctime(&txTm) << std::endl;return 0;
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/8639.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Hikyuu-PF-银行股轮动交易策略实现

今天&#xff0c;带来的是“如何使用 Hikyuu 中的投资组合来实现银行股轮动交易策略”。 这个策略的逻辑很简单&#xff1a;持续持有两支市净率最低银行股&#xff0c;然后每月换仓 定义回测周期与回测标的 同样&#xff0c;首先定义回测周期&#xff1a; # 定义回测日期 …

撰写一份详尽的数据治理实施方案

对于拥有15年经验的资深数据治理工程师而言,是一个复杂而细致的任务,应当涵盖策略规划、组织架构调整、技术选型、流程设计、合规性考量、监控与评估等多个维度。本文概述一个高层次的数据治理实施方案框架,并简要说明每个部分的关键内容。如需深入细节,您可以根据这个框架…

了解内存函数

✨✨欢迎&#x1f44d;&#x1f44d;点赞☕️☕️收藏✍✍评论 个人主页&#xff1a;秋邱博客 所属栏目&#xff1a;C语言 前言 内存函数不止malloc、calloc、realloc、free还有memcpy、memmove、memset、memcmp。前四个的头文件是<stdlib.h>,后四个的头文件是<strin…

Ansible----playbook模块之templates模块、tags模块、roles模块

目录 引言 一、templates模块 &#xff08;一&#xff09;关键信息 &#xff08;二&#xff09;实际操作 1.定义主机组 2.设置免密登录 3.分别建立访问目录 4.定义模板文件 5.创建playbook文件 6.执行剧本 7.验证结果 二、tags模块 &#xff08;一&#xff09;创建…

《QT实用小工具·六十一》带动画的三角形指示箭头

1、概述 源码放在文章末尾 该项目实现了一个带动画效果的三角形指示箭头&#xff0c;项目demo演示如下所示&#xff1a; 用法 interestingindicate.h interestingindicate.cpp 放到工程中&#xff0c;直接使用即可。 注意&#xff1a;建议绝对布局&#xff0c;手动指定 wid…

git stash技巧

1.缘由 有时代码写到一半有新bug要修复&#xff0c;这时可以先暂存当前代码&#xff08;使用git stash&#xff09;&#xff0c;修复完bug再回到原先的暂存文件&#xff08;使用git stash pop&#xff09;继续工作。 2.git stash的常用命令&#xff1a; &#xff08;1&#x…

【大数据】containered学习笔记

文章目录 1. Containerd安装1.1 YUM方式安装 【后端&网络&大数据&数据库目录贴】 1. Containerd安装 1.1 YUM方式安装 获取YUM源 获取阿里云YUM源 wget -O /etc/yum.repos.d/docker-ce.repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo 查…

华为车BU迈入新阶段,新任CEO对智能车的3个预判

作者 |张马也 编辑 |德新 4月24日&#xff0c;北京车展前夕&#xff0c;华为召开了新一年的智能汽车解决方案新品发布会。 这次发布会&#xff0c;也是华为智能汽车解决方案BU&#xff08;简称「车BU」&#xff09;CEO 靳玉志的公开首秀。 一开场&#xff0c;靳玉志即抛出了…

BACnet转MQTT网关智联楼宇json格式自定义

智能建筑的BACnet协议作为楼宇自动化领域的通用语言&#xff0c;正逐步迈向更广阔的物联网世界。随着云计算和大数据技术的飞速发展&#xff0c;如何将BACnet设备无缝融入云端生态系统&#xff0c;成为众多楼宇管理者关注的焦点。本文将以一个实际案例&#xff0c;揭示BACnet网…

Clion STM32CubeMX 项目

系列文章目录 前言 最后修改 2024 年 4 月 16 日 操作系统&#xff1a;Windows / Linux / macOS 所需工具 STM32CubeMX、GNU ARM 工具链 项目格式&#xff1a; CMake 兼容配置&#xff1a; OpenOCD 运行与调试/嵌入式 GDB 服务器 对于以 STM32 板卡为目标的嵌入式项目&#xf…

分布式与一致性协议之ZAB协议(七)

ZAB协议 ZAB协议:如何处理读写请求 你应该有这样的体会&#xff0c;如果你想了解一个网络服务&#xff0c;执行的第一个功能肯定是写操作&#xff0c;然后才会执行读操作。比如&#xff0c;你要了解ZooKeeper&#xff0c;那么肯定会在zkClient.sh命令行中执行写操作(比如crea…

如何购买阿里云99计划的ECS云服务器?99元购买阿里云2核2G3M服务器教程

阿里云助力中小企业和开发者无忧上云的“99计划”中有两款性价比超高的ECS云服务器&#xff0c;2026年3月31日活动结束前新购和续费价格一样。 其中个人和企业新老用户同享的2核2G3M服务器仅需99元/年&#xff08;续费同价&#xff09;&#xff0c;企业新老用户同学的2核4G5M仅…

Python 框架安全:Django SQL注入漏洞测试.(CVE-2021-35042)

什么是 Django 框架 Django 是一个用 Python 编写的 Web 应用程序框架。它提供了许多工具和库&#xff0c;使得开发 Web 应用程序变得更加容易和高效。Django 遵循了“MTV”&#xff08;模型-模板-视图&#xff09;的设计模式&#xff0c;将应用程序的不同组件分离开来&#x…

Leetcode 637:二叉树的层平均值

给定一个非空二叉树的根节点 root , 以数组的形式返回每一层节点的平均值。与实际答案相差 10-5 以内的答案可以被接受。 思路&#xff1a;其实就是计算每一层的和&#xff0c;再求平均值。 public static List<Double> averageOfLevels(TreeNode root) {List<Doubl…

《从零开始,搭建一个简单的UVM验证平台》实操

最近的工作中需要用UVM平台去仿真软件同事写的C程序&#xff0c;虽然只要用EDA同事已经搭好的UVM平台稍微改改就行&#xff0c;但对于我这种从未接触过UVM甚至都没用过System Verilog的纯FPGA工程师来说还是很有难度的&#xff0c;因为我对这方面一点概念都没有。 基于此&…

[Kubernetes] 安装KubeSphere

选择4核8G&#xff08;master&#xff09;、8核16G&#xff08;node1&#xff09;、8核16G&#xff08;node2&#xff09; 三台机器&#xff0c;按量付费进行实验&#xff0c;CentOS7.9安装Docker安装Kubernetes安装KubeSphere前置环境: nfs和监控安装KubeSphere masternode1no…

整理好了!2024年最常见 100 道 Java基础面试题(三十五)

上一篇地址&#xff1a;整理好了&#xff01;2024年最常见 100 道 Java基础面试题&#xff08;三十四&#xff09;-CSDN博客 六十九、接口是否可以继承接口&#xff1f; 在Java中&#xff0c;接口可以继承其他接口。这种继承关系允许一个接口扩展另一个接口中定义的常量和抽象…

STL——函数对象和谓词

函数对象 概念 重载函数调用操作符()的类&#xff0c;其对象常被称为仿函数 函数对象使用重载的()时&#xff0c;行为类似函数调用&#xff0c;也叫做仿函数 本质上仿函数是一个类&#xff0c;并不是一个函数 函数对象使用 函数对象在使用时&#xff0c;可以像普通函数一样…

【QT学习】14.线程学习

一。线程了解 线程是计算机科学中的一个重要概念&#xff0c;它是操作系统能够进行运算调度的最小单位。线程是进程中的一个执行流&#xff0c;一个进程可以包含多个线程。与进程相比&#xff0c;线程更轻量级&#xff0c;可以更高效地利用计算机资源。 线程有以下几个特点&…

Spring Boot应用部署 - Tomcat容器替换为Undertow容器

Tomcat容器替换为Undertow容器 要在Spring Boot应用中将默认的Tomcat容器替换为Undertow容器&#xff0c;可以按照以下步骤进行操作&#xff1a; Maven项目配置 排除Tomcat依赖&#xff1a;首先&#xff0c;你需要从spring-boot-starter-web依赖中排除Tomcat。在你的pom.xml文…