using System.Net;
using System.Net.Sockets;
命名空间时钟{公共部分类Form1:表格{公共Form1(){InitializeComponent();}
private void button1_Click(object sender, EventArgs e)
{
label1.Text = GetNetworkTime().ToString(); //show date and time in label1
}
public static DateTime GetNetworkTime()
{
const string ntpServer = "time.windows.com";
/*
time-a.nist.gov 129.6.15.28 NIST, Gaithersburg, Maryland
time-b.nist.gov 129.6.15.29 NIST, Gaithersburg, Maryland
time-a.timefreq.bldrdoc.gov 132.163.4.101 NIST, Boulder, Colorado
time-b.timefreq.bldrdoc.gov 132.163.4.102 NIST, Boulder, Colorado
time-c.timefreq.bldrdoc.gov 132.163.4.103 NIST, Boulder, Colorado
utcnist.colorado.edu 128.138.140.44 University of Colorado, Boulder
time.nist.gov 192.43.244.18 NCAR, Boulder, Colorado
time-nw.nist.gov 131.107.1.10 Microsoft, Redmond, Washington
nist1.datum.com 209.0.72.7 Datum, San Jose, California
nist1.dc.certifiedtime.com 216.200.93.8 Abovnet, Virginia
nist1.nyc.certifiedtime.com 208.184.49.9 Abovnet, New York City
nist1.sjc.certifiedtime.com 208.185.146.41 Abovnet, San Jose, California
*/
var ntpData = new byte[48];
ntpData[0] = 0x1B; //LeapIndicator = 0 (no warning), VersionNum = 3 (IPv4 only), Mode = 3 (Client Mode)
var addresses = Dns.GetHostEntry(ntpServer).AddressList;
var ipEndPoint = new IPEndPoint(addresses[0], 123);
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Connect(ipEndPoint);
socket.Send(ntpData);
socket.Receive(ntpData);
socket.Close();
ulong intPart = (ulong)ntpData[40] << 24 | (ulong)ntpData[41] << 16 | (ulong)ntpData[42] << 8 | (ulong)ntpData[43];
ulong fractPart = (ulong)ntpData[44] << 24 | (ulong)ntpData[45] << 16 | (ulong)ntpData[46] << 8 | (ulong)ntpData[47];
var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);
DateTime networkDateTime = (new DateTime(1900, 1, 1)).AddMilliseconds((long)milliseconds);
return networkDateTime;
}
}
}