C#获取互联网时间

  1 public static class TimeHelper
  2     {
  3         // 小端存储与大端存储的转换
  4         private static uint swapEndian(ulong x)
  5         {
  6             return (uint)(((x & 0x000000ff) << 24) +
  7             ((x & 0x0000ff00) << 8) +
  8             ((x & 0x00ff0000) >> 8) +
  9             ((x & 0xff000000) >> 24));
 10         }
 11 
 12         // 方法1、获取NTP网络时间
 13         public static DateTime getWebTime()
 14         {
 15             // default ntp server
 16             const string ntpServer = "ntp1.aliyun.com";
 17 
 18             // NTP message size - 16 bytes of the digest (RFC 2030)
 19             byte[] ntpData = new byte[48];
 20             // Setting the Leap Indicator, Version Number and Mode values
 21             ntpData[0] = 0x1B; // LI = 0 (no warning), VN = 3 (IPv4 only), Mode = 3 (Client Mode)
 22 
 23             IPAddress[] addresses = Dns.GetHostEntry(ntpServer).AddressList;
 24             foreach (var item in addresses)
 25             {
 26                 Debug.WriteLine("IP:" + item);
 27             }
 28 
 29             // The UDP port number assigned to NTP is 123
 30             IPEndPoint ipEndPoint = new IPEndPoint(addresses[0], 123);
 31 
 32             // NTP uses UDP
 33             Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
 34             socket.Connect(ipEndPoint);
 35             // Stops code hang if NTP is blocked
 36             socket.ReceiveTimeout = 3000;
 37             socket.Send(ntpData);
 38             socket.Receive(ntpData);
 39             socket.Close();
 40 
 41             // Offset to get to the "Transmit Timestamp" field (time at which the reply 
 42             // departed the server for the client, in 64-bit timestamp format."
 43             const byte serverReplyTime = 40;
 44             // Get the seconds part
 45             ulong intPart = BitConverter.ToUInt32(ntpData, serverReplyTime);
 46             // Get the seconds fraction
 47             ulong fractPart = BitConverter.ToUInt32(ntpData, serverReplyTime + 4);
 48             // Convert From big-endian to little-endian
 49             intPart = swapEndian(intPart);
 50             fractPart = swapEndian(fractPart);
 51             ulong milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000UL);
 52 
 53             // UTC time
 54             DateTime webTime = (new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc)).AddMilliseconds(milliseconds);
 55             // Local time
 56             return webTime.ToLocalTime();
 57         }
 58 
 59         //方法2、获取ntp时间
 60         public static DateTime DataStandardTime()//使用时,将static 关键字删除,在其它位置方可使用?2010-11-24
 61         {//返回国际标准时间
 62             //只使用的TimerServer的IP地址,未使用域名
 63             string[,] TimerServer = new string[14, 2];
 64             int[] ServerTab = new int[] { 3, 2, 4, 8, 9, 6, 11, 5, 10, 0, 1, 7, 12 };
 65 
 66             TimerServer[0, 0] = "time-a.nist.gov";
 67             TimerServer[0, 1] = "129.6.15.28";
 68             TimerServer[1, 0] = "time-b.nist.gov";
 69             TimerServer[1, 1] = "129.6.15.29";
 70             TimerServer[2, 0] = "time-a.timefreq.bldrdoc.gov";
 71             TimerServer[2, 1] = "132.163.4.101";
 72             TimerServer[3, 0] = "time-b.timefreq.bldrdoc.gov";
 73             TimerServer[3, 1] = "132.163.4.102";
 74             TimerServer[4, 0] = "time-c.timefreq.bldrdoc.gov";
 75             TimerServer[4, 1] = "132.163.4.103";
 76             TimerServer[5, 0] = "utcnist.colorado.edu";
 77             TimerServer[5, 1] = "128.138.140.44";
 78             TimerServer[6, 0] = "time.nist.gov";
 79             TimerServer[6, 1] = "192.43.244.18";
 80             TimerServer[7, 0] = "time-nw.nist.gov";
 81             TimerServer[7, 1] = "131.107.1.10";
 82             TimerServer[8, 0] = "nist1.symmetricom.com";
 83             TimerServer[8, 1] = "69.25.96.13";
 84             TimerServer[9, 0] = "nist1-dc.glassey.com";
 85             TimerServer[9, 1] = "216.200.93.8";
 86             TimerServer[10, 0] = "nist1-ny.glassey.com";
 87             TimerServer[10, 1] = "208.184.49.9";
 88             TimerServer[11, 0] = "nist1-sj.glassey.com";
 89             TimerServer[11, 1] = "207.126.98.204";
 90             TimerServer[12, 0] = "nist1.aol-ca.truetime.com";
 91             TimerServer[12, 1] = "207.200.81.113";
 92             TimerServer[13, 0] = "nist1.aol-va.truetime.com";
 93             TimerServer[13, 1] = "64.236.96.53";
 94             int portNum = 13;
 95             string hostName;
 96             byte[] bytes = new byte[1024];
 97             int bytesRead = 0;
 98             System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient();
 99             for (int i = 0; i < 13; i++)
100             {
101                 hostName = TimerServer[ServerTab[i], 0];
102 
103                 Debug.WriteLine("hostName:" + hostName);
104                 try
105                 {
106                     client.Connect(hostName, portNum);
107 
108                     System.Net.Sockets.NetworkStream ns = client.GetStream();
109                     bytesRead = ns.Read(bytes, 0, bytes.Length);
110                     client.Close();
111                     break;
112                 }
113                 catch (System.Exception)
114                 {
115                     Debug.WriteLine("错误!");
116                 }
117             }
118             char[] sp = new char[1];
119             sp[0] = ' ';
120             System.DateTime dt = new DateTime();
121             string str1;
122             str1 = System.Text.Encoding.ASCII.GetString(bytes, 0, bytesRead);
123             Debug.WriteLine("ntp time:" + str1);
124 
125             string[] s;
126             s = str1.Split(sp);
127             dt = System.DateTime.Parse(s[1] + " " + s[2]);//得到标准时间
128             Debug.WriteLine("get:" + dt.ToShortTimeString());
129             //dt=dt.AddHours (8);//得到北京时间*/
130             return dt;
131 
132         }
133 
134         //方法3、获取网页时间
135 
136         //Bdpagetype:2
137         //Bdqid:0xaff4e50f00011b53
138         //Cache-Control:private
139         //Connection:Keep-Alive
140         //Content-Encoding:gzip
141         //Content-Type:text/html;charset=utf-8
142         //Date:Tue, 23 Oct 2018 03:24:38 GMTv
143         public static string GetNetDateTime()
144         {
145             WebRequest request = null;
146             WebResponse response = null;
147             WebHeaderCollection headerCollection = null;
148             string datetime = string.Empty;
149             try
150             {
151                 request = WebRequest.Create("https://www.baidu.com");
152                 request.Timeout = 1000;
153                 request.Credentials = CredentialCache.DefaultCredentials;
154                 response = (WebResponse)request.GetResponse();
155                 headerCollection = response.Headers;
156                 foreach (var h in headerCollection.AllKeys)
157                 { if (h == "Date") { datetime = headerCollection[h]; } }
158                 return datetime;
159             }
160             catch (Exception) { return datetime; }
161             finally
162             {
163                 if (request != null)
164                 { request.Abort(); }
165                 if (response != null)
166                 { response.Close(); }
167                 if (headerCollection != null)
168                 { headerCollection.Clear(); }
169             }
170         }
171 
172     }
View Code

--摘自其他用户

转载于:https://www.cnblogs.com/huangtaiyi/p/11162396.html

你可能感兴趣的:(C#获取互联网时间)