收到一个需要定时同步远程服务器的需求,用C# 实现

网上搜索到解决方案,代码如下:

获取远程时间

参数配置:"NTPServer"  远程时间服务器地址

获取远程服务器时间代码:

public class NTPTimeHelper
{
/// <summary>
/// 获取NTC时间
/// </summary>
/// <returns></returns>
public static DateTime GetNetworkTime()
{ //default Windows time server
string ntpServer = ConfigHelper.GetConfigToStr("NTPServer", ""); // NTP message size - 16 bytes of the digest (RFC 2030)
var ntpData = new byte[48]; //Setting the Leap Indicator, Version Number and Mode values
ntpData[0] = 0x1B; //LI = 0 (no warning), VN = 3 (IPv4 only), Mode = 3 (Client Mode) var addresses = Dns.GetHostEntry(ntpServer).AddressList; //The UDP port number assigned to NTP is 123
var ipEndPoint = new IPEndPoint(addresses[0], 123);
//NTP uses UDP
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); socket.Connect(ipEndPoint); //Stops code hang if NTP is blocked
socket.ReceiveTimeout = 3000; socket.Send(ntpData);
socket.Receive(ntpData);
socket.Close(); //Offset to get to the "Transmit Timestamp" field (time at which the reply
//departed the server for the client, in 64-bit timestamp format."
const byte serverReplyTime = 40; //Get the seconds part
ulong intPart = BitConverter.ToUInt32(ntpData, serverReplyTime); //Get the seconds fraction
ulong fractPart = BitConverter.ToUInt32(ntpData, serverReplyTime + 4); //Convert From big-endian to little-endian
intPart = SwapEndianness(intPart);
fractPart = SwapEndianness(fractPart); var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L); //**UTC** time
var networkDateTime = (new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc)).AddMilliseconds((long)milliseconds); return networkDateTime.ToLocalTime();
} // stackoverflow.com/a/3294698/162671
static uint SwapEndianness(ulong x)
{
return (uint)(((x & 0x000000ff) << 24) +
((x & 0x0000ff00) << 8) +
((x & 0x00ff0000) >> 8) +
((x & 0xff000000) >> 24));
}
}

  获取服务器后修改本地服务器时间:

/// <summary>
///
/// </summary>
internal struct SYSTEMTIME
{
public ushort wYear;
public ushort wMonth;
public ushort wDayOfWeek;
public ushort wDay;
public ushort wHour;
public ushort wMinute;
public ushort wSecond;
public ushort wMilliseconds; /// <summary>
/// 从System.DateTime转换。
/// </summary>
/// <param name="time">System.DateTime类型的时间。</param>
public void FromDateTime(DateTime time)
{
wYear = (ushort)time.Year;
wMonth = (ushort)time.Month;
wDayOfWeek = (ushort)time.DayOfWeek;
wDay = (ushort)time.Day;
wHour = (ushort)time.Hour;
wMinute = (ushort)time.Minute;
wSecond = (ushort)time.Second;
wMilliseconds = (ushort)time.Millisecond;
}
/// <summary>
/// 转换为System.DateTime类型。
/// </summary>
/// <returns></returns>
public DateTime ToDateTime()
{
return new DateTime(wYear, wMonth, wDay, wHour, wMinute, wSecond, wMilliseconds);
}
/// <summary>
/// 静态方法。转换为System.DateTime类型。
/// </summary>
/// <param name="time">SYSTEMTIME类型的时间。</param>
/// <returns></returns>
public static DateTime ToDateTime(SYSTEMTIME time)
{
return time.ToDateTime();
}
}
internal class Win32API
{
[DllImport("Kernel32.dll")]
public static extern bool SetLocalTime(ref SYSTEMTIME Time);
[DllImport("Kernel32.dll")]
public static extern void GetLocalTime(ref SYSTEMTIME Time);
} public class SystemHelper
{
public static void SetLocalMachineTime(DateTime dt)
{
//转换System.DateTime到SYSTEMTIME
SYSTEMTIME st = new SYSTEMTIME();
st.FromDateTime(dt);
//调用Win32 API设置系统时间
Win32API.SetLocalTime(ref st);
}
}

  这样就可以了。

本文引用:http://xqblog.top/Article.aspx?id=ART2018040200001

C# 获取NTP远程同步时间的更多相关文章

  1. linux 下使rdate命令支持ipv6 ntp server 同步时间

    如果使用linux 下,busybox自带的rdate命令 去ipv6 的ntp server 同步时间的话,会提示invalid argument :无效参数. 那么现在下载rdate的源码并对其进 ...

  2. VMware ESXi 5.5无法与Windows 2012 NTP Server同步时间

    这次笔者需要面对的环境对时间的同步有比较高的要求, 而虚拟化的环境中时间是比较容易出问题的, 您可以参考上一篇博文为什么Domain controller上的time synchronization非 ...

  3. Centos7安装搭建NTP服务器和NTP客户端同步时间

    NTP简介: NTP是网络时间协议(Network Time Protocol),它是用来同步网络中各个计算机的时间的协议. 在计算机的世界里,时间非常地重要 例如:对于火箭发射这种科研活动,对时间的 ...

  4. Centos7部署ntp服务器同步时间以及直接将本地时间同步为北京时间

    一.查看配置 查看时区列表: timedatectl list-timezones|grep Asia 查看当前时间: date 查看当前设置: [root@localhost ~]# timedat ...

  5. ntp服务器同步时间详细配置

    部署NTP服务器进行时间同步   NTP服务端:linl_S    IP:10.0.0.15 NTP客户端:lin_C    IP:10.0.0.16 NTP服务概述 1.原理 NTP(Network ...

  6. 利用ntp自动同步时间

    实验环境:centos 6.10 1.安装ntp工具 yum install -y ntp 2.便宜/etc/ntp.conf文件,添加远程时间服务器 server ntp1.aliyun.com s ...

  7. centos7开启ntp并同步时间到指定时区

    前提:近期公司都是使用的直接对外的云服务器,在登上服务器后用date命令查看新服务器的时间,发现并不是标准时间,于是需要做时间同步.我这里讲的是能连接外网的情况下,在服务器不多的情况下是否此方法,大型 ...

  8. 同步时间linux

    针对对时间要求精确度高的服务器 1.安装时间服务器yum install ntp 2.同步时间ntpdate time.nist.gov 3.设置计划任务每隔10分钟同步一次 */10 * * * * ...

  9. CentOS同步时间

    用date查看系统当前时间,date -R 可查看时区. CentOS 同步时间由ntp服务提供,可以用"yum install ntp -y"安装. 装完后运行命令 ntpdat ...

随机推荐

  1. Spring Boot 2.x零基础入门到高级实战教程

    一.零基础快速入门SpringBoot2.0 1.SpringBoot2.x课程全套介绍和高手系列知识点 简介:介绍SpringBoot2.x课程大纲章节 java基础,jdk环境,maven基础 2 ...

  2. MySql-8.0.12 安装教程随笔

    下载地址: https://www.mysql.com/downloads/ 现在最下边的社区版本,也就是免费版本 之后我们会看到有两个选择的下载,一个为zip压缩包格式,一个是Install版本,个 ...

  3. 关于多行文本 textarea 在ios 真机上padding相对安卓较大问题

    问题: 多行文本组件是带有默认的padding的,然而,小程序的teatarea 在ios和安卓上显示的padding不一样,普遍ios的padding会比安卓的要明显的大.这种情况下我的想法是做兼容 ...

  4. linux正则表达式企业级深度实践案例1

    linux正则表达式结合三剑客企业级实践: 1.取系统ip [root@redhat~]#  ifconfig  eth0 解答: 替换命令: sed  's#支持正则位置##g'  file 先取第 ...

  5. 文档对象模型 DOM

    1 DOM概述 1.1 什么是DOM 文档对象模型 Document Object Model 文档对象模型 是表示和操作 HTML和XML文档内容的基础API 文档对象模型,是W3C组织推荐的处理可 ...

  6. C语言中float如何存储?(转载)

    float 内存如何存储的 类型 存储位数 总位数 偏移值(offset) 数符(S) 阶码(E) 尾数(M) 短实数(float) 1 8 23 32 127 长实数(double) 1 11 52 ...

  7. 动态规划:POJ2576-Tug of War(二维费用的背包问题)

    Tug of War Time Limit: 3000MS Memory Limit: 65536K Description A tug of war is to be arranged at the ...

  8. 朴素贝叶斯python小样本实例

    朴素贝叶斯优点:在数据较少的情况下仍然有效,可以处理多类别问题缺点:对于输入数据的准备方式较为敏感适用数据类型:标称型数据朴素贝叶斯决策理论的核心思想:选择具有最高概率的决策朴素贝叶斯的一般过程(1) ...

  9. TCP报文格式,TCP的三次握手和四次挥手&hosts文件

    1.TCP报文格式 TCP报头中的源端口号和目的端口号同IP数据报中的源IP与目的IP唯一确定一条TCP连接 序号(4字节=32位): 37 59 56 75 用来标识TCP发端向TCP收端发送的数据 ...

  10. python 二——函数、装饰器、生成器、面向对象编程(初级)

    本节内容 1.函数 2.装饰器 3.生成器 4.类 一.函数 函数式:将某功能代码封装到函数中,日后便无需重复编写,仅调用函数即可 面向对象:对函数进行分类和封装,让开发“更快更好更强...” 函数式 ...