收到一个需要定时同步远程服务器的需求,用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. GreenPlum查看表和数据库大小

    表大小 zwcdb=# select pg_size_pretty(pg_relation_size('gp_test')); pg_size_pretty ---------------- 1761 ...

  2. FTP、SFTP与FTPS

    先简单介绍下FTP的基础知识 FTP的传输有两种方式:ASCII.二进制. FTP支持两种模式:Standard (PORT方式,主动方式),Passive (PASV,被动方式). 主动模式 FTP ...

  3. web前端的环境配置

    1.1.WEB开发的相关知识 WEB,在英语中web即表示网页的意思,它用于表示Internet主机上供外界访问的资源. Internet上供外界访问的Web资源分为: 静态web资源(如html 页 ...

  4. spring boot 设置tomcat post参数限制

    今天传图片,用的base64字符串,POST方法,前端传送的时候总是莫名其妙的崩溃,去网上搜了半天,以为是文件大小被限制了,但是我这个是字符串接收,不是文件接收,于是又继续搜,原来post本身没有参数 ...

  5. 【转】iPhone通讯录AddressBook.framework和AddressBookUI.framework的应用

    通讯录中联系人相关的应用iPhone提供了两个框架:AddressBook.framework和AddressBookUI.framework,使用这两个框架我们可以在程序中访问并显示iPhone数据 ...

  6. 2015-2016 Northwestern European Regional Contest (NWERC 2015)

    训练时间:2019-04-05 一场读错三个题,队友恨不得手刃了我这个坑B. A I J 简单,不写了. C - Cleaning Pipes (Gym - 101485C) 对于有公共点的管道建边, ...

  7. “帮你APP”团队冲刺7

    1.整个项目预期的任务量 (任务量 = 所有工作的预期时间)和 目前已经花的时间 (所有记录的 ‘已经花费的时间’),还剩余的时间(所有工作的 ‘剩余时间’) : 所有工作的预期时间:88h 目前已经 ...

  8. centos使用--vsftpd配置

    目录 1 在服务器配置FTP服务 1.1 在root权限下,通过如下命令安装Vsftp(以CentOS系统为例): 1.2 在启动vsftpd服务之前,需要登录云服务器修改配置文件,禁用匿名登录. 1 ...

  9. DEDE调用指定文章ID来调用特定文档

    http://www.jb51.net/cms/137423.html 代码如下: {dede:arclist row=1 idlist='6'} <li><a href=" ...

  10. 设计模式之第4章-装饰模式(Java实现)

    设计模式之第4章-装饰模式(Java实现) “怎么了,鱼哥?” “唉,别提了,网购了一件衣服,结果发现和商家描述的差太多了,有色差就算了,质量还不好,质量不好就算了,竟然大小也不行,说好的3个X,邮的 ...