收到一个需要定时同步远程服务器的需求,用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. cookie 和 localStorage 、sessionStorage、 session不同

    1. cookie:存储大小4k 有时间限制,会跟在ajax的请求头上 2. localStorage: 存储大小5M 没有时间限制 3. sessionStorage: 临时会话存储 当浏览器关闭的 ...

  2. neo4j 安装

    查看 http://ip:7474/browser/

  3. 二十三、MySQL 事务

    MySQL 事务 MySQL 事务主要用于处理操作量大,复杂度高的数据.比如说,在人员管理系统中,你删除一个人员,你即需要删除人员的基本资料,也要删除和该人员相关的信息,如信箱,文章等等,这样,这些数 ...

  4. Java 技术栈

    JAVA是一个面向对象的编程语言,由SUN公司的程序员所开发.它不仅吸收了C++的各种优点,而且还撇弃了C++中难以理解的概念,如多继承.指针等:因此JAVA语言具有功能强大且简单易用两个特征, JA ...

  5. WebUploader压缩图片上传

    WebUploader,由Baidu FEX 团队开发,以H5为主,FLASH为辅,兼容 IE6+,iOS 6+, android 4+,采用大文件分片并发上传,极大的提高了文件上传效率,看了官方文档 ...

  6. python3:判断手机的亮屏状态

    在用python对手机做一些自动化操作时,常常会判断手机的亮屏状态,知晓手机的亮屏状态后才好做进一步的动作,如给屏幕解锁等.  用于了解手机的亮屏情况,有一个adb命令可用: adb shell du ...

  7. oracle 事务 第一弹

    一.事务概念 概念:在数据库中事务是工作的逻辑单元,一个事务是由一个或多个完成一组的相关行为的SQL语句组成,通过事务机制确保这一组SQL语句所作的操作要么完全成功执行,完成整个工作单元操作,要么一点 ...

  8. [Hdu1693]Eat the Trees(插头DP)

    Description 题意:在n*m(1<=N, M<=11 )的矩阵中,有些格子有树,没有树的格子不能到达,找一条或多条回路,吃完所有的树,求有多少种方法. Solution 插头DP ...

  9. 纯javascript验证,100行超精简代码。

    这篇文章转自--寒飞,原帖地址http://blog.csdn.net/luoyehanfei/article/details/42262249 QQ交流群235032949 纯javascript验 ...

  10. Autofac Mvc5 Nuget

    Autofac 3.5.2 Install-Package Autofac -Version 3.5.2 Autofac ASP.NET MVC 5 Integration 3.3.3 Install ...