public static DateTime Getnetworktime ()
{
Default Windows time Server
Const string ntpServer = "1.cn.pool.ntp.org";
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 * +) + ((Fractpart * +)/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));
}
C # Gets the NTP time for the corresponding IP