C # Gets the NTP time for the corresponding IP

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.