c# Internet时间服务器同步
需要用到的名空间
- using System.Net;
- using System.Net.Sockets;
- using System.Runtime.InteropServices;
建立一个结构
- public 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();
- }
- }
要用到Windows的API函数来设置系统时间
- public class Win32API
- {
- [DllImport("Kernel32.dll")]
- public static extern bool SetLocalTime(ref SystemTime Time);
- [DllImport("Kernel32.dll")]
- public static extern void GetLocalTime(ref SystemTime Time);
- }
用Socket获取Internet时间服务器上的时间
- public void SetInternetTime()
- {
- // 记录开始的时间
- DateTime startDT = DateTime.Now;
- //建立IPAddress对象与端口,创建IPEndPoint节点:
- int port = 13;
- string[] whost = { "5time.nist.gov", "time-nw.nist.gov", "time-a.nist.gov", "time-b.nist.gov", "tick.mit.edu", "time.windows.com", "clock.sgi.com" };
- IPHostEntry iphostinfo;
- IPAddress ip;
- IPEndPoint ipe;
- Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建Socket
- c.ReceiveTimeout = 10 * 1000;//设置超时时间
- string sEX = "";// 接受错误信息
- // 遍历时间服务器列表
- foreach (string strHost in whost)
- {
- try
- {
- iphostinfo = Dns.GetHostEntry(strHost);
- ip = iphostinfo.AddressList[0];
- ipe = new IPEndPoint(ip, port);
- c.Connect(ipe);//连接到服务器
- if (c.Connected) break;// 如果连接到服务器就跳出
- }
- catch (Exception ex)
- {
- sEX = ex.Message;
- }
- }
- if (!c.Connected)
- {
- MessageBox.Show("时间服务器连接失败!/r错误信息:" + sEX, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
- return;
- }
- //SOCKET同步接受数据
- byte[] RecvBuffer = new byte[1024];
- int nBytes, nTotalBytes = 0;
- StringBuilder sb = new StringBuilder();
- System.Text.Encoding myE = Encoding.UTF8;
- while ((nBytes = c.Receive(RecvBuffer, 0, 1024, SocketFlags.None)) > 0)
- {
- nTotalBytes += nBytes;
- sb.Append(myE.GetString(RecvBuffer, 0, nBytes));
- }
- //关闭连接
- c.Close();
- string[] o = sb.ToString().Split(' '); // 打断字符串
- textBox1.Text = sb.ToString();
- TimeSpan k = new TimeSpan();
- k = (TimeSpan)(DateTime.Now - startDT);// 得到开始到现在所消耗的时间
- DateTime SetDT = Convert.ToDateTime(o[1] + " " + o[2]).Subtract(-k);// 减去中途消耗的时间
- //处置北京时间 +8时
- SetDT = SetDT.AddHours(8);
- //转换System.DateTime到SystemTime
- SystemTime st = new SystemTime();
- st.FromDateTime(SetDT);
- //调用Win32 API设置系统时间
- Win32API.SetLocalTime(ref st);
- MessageBox.Show("时间已同步", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
- }
这个东西是收集网上的一些做法再修改了一下
用vs2008+windows xp sp2测试通过
但是始终会有±1秒的误差,但大部分误差在1秒以下,尚可接受
使用的名空间包括vs自己添加的,windows Form中用到的那部分
如果换了环境,可作相应修改
转载:http://blog.csdn.net/zhengxia19/article/details/3858910
c# Internet时间服务器同步的更多相关文章
- VC自动与Internet时间服务器同步更新
在VCKBASE.CSDN里挖了许久的坟,才找到一些有点用的资料,最后自己整理出这样的个函数,方面VC实现时间同步,多的不说,自己看源码,根据自己的需要可以适当修改源码: #include <W ...
- 小凡的Linux主机与时间服务器同步记录
小凡的Linux主机与时间服务器同步记录 导读 我们新安装的Linux主机,如果没有做与互联网服务器时间同步的处理的话,当我们使用date命令的时候,我们就看不到当前的时间,只能看到过去的时间.在我们 ...
- 设置linux服务器定时与时间服务器同步
在一些大公司经常出现这样一个情况:公司或一些机关单位的内部业务系统的应用服务器以及数据都是做的多机集群部署而且基本都是linux系统,而且都是内部网,不与外网通讯的.这样经常就会出现一个情况,我发送任 ...
- 自动与因特网时间服务器同步 NTP 服务器 pool.ntp.org, 120.24.166.46 端口 123
自动与因特网时间服务器同步 NTP 服务器 pool.ntp.org 海康提供的NTP服务器 120.24.166.46 端口 123
- centos下部署NTP时间服务器同步环境记录
1)服务端部署 安装所需软件包 [root@test ~]# yum -y install ntp ntpdate 服务端自己先手工同步一次时间. [root@test ~]# ntpdate ntp ...
- Linux基础命令---ntpstat显示时间服务器同步
ntpstat ntpstat指令用于显示本机上一次和服务器同步时间的情况. 此命令的适用范围:RedHat.RHEL.Ubuntu.CentOS.Fedora. 1.语法 ntpstat 2 ...
- 分享淘宝时间服务器同步时间接口api和苏宁时间服务器接口api
最近要开发一款抢购秒杀的小工具,需要同步系统时间,这里分享两个时间服务器接口api给大家: 1.淘宝时间服务器时间接口 http://api.m.taobao.com/rest/api3.do?api ...
- chronyd时间服务器同步时间配置
chrony是两个用来维持计算机系统时钟准确性的程序,这两个程序命名为chronyd和chronyc. chronyd是一个在系统后台运行的守护进程.他根据网络上其他时间服务器时间来测量本机时间的偏移 ...
- linux下自动同步internet时间
linux下很简单直接一句即可: ntpdate time.nist.gov ntp后面参数为internet时间服务器url或ip即可. 但是ntpdate命令需要root特权,如果做成自动运行每次 ...
随机推荐
- [转]Jquery Ajax用法
原文地址:http://www.php100.com/html/program/jquery/2013/0905/6004.html jQuery学习之jQuery Ajax用法详解 来源: 时间 ...
- 解决魅族USB调试无法被电脑识别的问题(含Mac OS X、Win7)
每次打开豌豆荚或者360手机助手之类手机助手后Eclipse才会检测到mx4(实际上是豌豆荚关闭eclipse的adb使用自己的驱动连接的).解决方法就是在"adb_usb.ini&qu ...
- cocos2d-x 小技巧
1.字符串 与 数据结构互转 CCPoint: CCPointFromString(); {x, y} CCSize: CCSizeFromString(); {w, h} CCRect: CCSiz ...
- Reading or Writing to Another Processes Memory in C# z
http://www.jarloo.com/reading-and-writing-to-memory/ Declarations [Flags] public enum ProcessAccessF ...
- BLOCK 死循环
__weak typeof(self) weakSelf = self; myObj.myBlock = ^{ __strong typeof(self) strongSelf = weak ...
- ASM基本操作
1. 添加一个磁盘组 SQL> create diskgroup recover external redundancy disk 'ORCL:kel3'; Diskgroup created. ...
- CSS计算样式的获取
一般来说我们获取CSS的样式的时候会优先采用Elment.style.cssName 这种方法,这种方法类似于对象设置get,set属性获取,例如Elment.style.cssName是获取,Elm ...
- 使用 CreateInstallMedia 创建 苹果系统安装U盘
一般来说,从app store上面 下载下来的image位置,都是在 /Applications 下面 使用命令创建安装U盘,(备份一下命令,太长,记不住) sudo /Applications/In ...
- 题目1434:今年暑假不AC (项目安排类:结束时间快排,判断开始时间)
题目描述: “今年暑假不AC?”“是的.”“那你干什么呢?”“看世界杯呀,笨蛋!”“@#$%^&*%...”确实如此,世界杯来了,球迷的节日也来了,估计很多ACMer也会抛开电脑,奔向电视作为 ...
- PhoneGap,Cordova[3.5.0-0.2.6]:生成Android项目时出现错误(An error occurred while listing Android targets)
我在升级到Cordova最新版本(3.5.0-0.2.6)后,在生成Android项目(cordova platform add android)时出现错误: Error: An error occu ...