C # obtain the standard network time

Source: Internet
Author: User

Using Microsoft. VisualBasic;
Using system;
Using system. collections;
Using system. Collections. Generic;
Using system. Data;
Using system. diagnostics;
Using system. IO;
Using system. net;
Using system. net. Sockets;
Using system. runtime. interopservices;
Namespace spider
{
Public class daytime
{
// Internet time server class by Alastair Dallas 01/27/04

// Number of seconds
Private const int threshold_seconds = 15;
// That Windows clock can deviate from NIST and still be okay

// Server IP addresses from
// Http://www.boulder.nist.gov/timefreq/service/time-servers.html
Private Static string [] servers = {
"129.6.15.28 ",
"129.6.15.29 ",
"13.03.4.101 ",
"13.03.4.102 ",
"13.03.4.103 ",
"128.138.140.44 ",
"192.43.244.18 ",
"131.107.1.10 ",
"66.243.43.21 ",
"216.200.93.8 ",
"208.184.49.9 ",
"207.126.98.204 ",
"205.188.185.33"

};
Public static string lasthost = "";

Public static datetime lastsystime;
Public static datetime gettime ()
{
// returns UTC/GMT using an NIST server if possible,
// degrading to simply returning the system clock

// if we are successful in getting NIST time, then
// lasthost indicates which server was used and
// lastpolicime contains the system time of the call
// If lastpolicime is not within 15 seconds of NIST time,
// The system clock may need to be reset
// If lasthost is "", time is equal to system clock

String host = NULL;
Datetime result = default (datetime );

Lasthost = "";
Foreach (string host_loopvariable in servers)
{
Host = host_loopvariable;
Result = getnisttime (host );
If (result> datetime. minvalue)
{
Lasthost = host;
Break; // todo: might not be correct. Was: exit
}
}

If (string. isnullorempty (lasthost ))
{
// No server in list was successful so use system time
Result = datetime. utcnow;
}

Return result;
}

Public static int secondsdifference (datetime dt1, datetime dt2)
{
timespan span = dt1.subtract (dt2 );
return span. seconds + (span. minutes * 60) + (span. hours * 360);
}

Public static bool windowsclockincorrect ()
{
datetime NIST = gettime ();
If (math. ABS (secondsdifference (NIST, lastpolicime)> threshold_seconds)
{
return true;
}
return false;
}

Private Static datetime getnisttime (string host)
{
// Returns datetime. minvalue if host unreachable or does not produce time
Datetime result = default (datetime );
String timestr = NULL;

Try
{
Streamreader reader = new streamreader (New tcpclient (host, 13). getstream ());
Lastpolicime = datetime. utcnow;
Timestr = reader. readtoend ();
Reader. Close ();
}
Catch (socketexception ex)
{
// Couldn't connect to server, Transmission Error
Debug. writeline ("socket exception [" + host + "]");
Return datetime. minvalue;
}
Catch (exception ex)
{
// Some other error, such as stream under/Overflow
Return datetime. minvalue;
}

// Parse timestr
If (timestr. substring (38, 9 )! = "UTC (NIST )"))
{
// This signature shocould be there
Return datetime. minvalue;
}
If (timestr. substring (30, 1 )! = "0 "))
{
// Server reports Non-optimum status, time off by as much as 5 seconds
Return datetime. minvalue;
// Try a different server
}

int JD = int. parse (timestr. substring (1, 5);
int yr = int. parse (timestr. substring (7, 2);
int mo = int. parse (timestr. substring (10, 2);
int DY = int. parse (timestr. substring (13, 2);
int hR = int. parse (timestr. substring (16, 2);
int Mm = int. parse (timestr. substring (19, 2);
int SC = int. parse (timestr. substring (22, 2);

If (JD <15020 ))
{
// Date is before 1900
return datetime. minvalue;
}
If (JD> 51544 ))
yr + = 2000;
else
yr ++ = 1900;

Return new datetime (yr, Mo, Dy, HR, mm, SC );

}

[Structlayout (layoutkind. Sequential)]
Public struct systemtime
{
Public int16 wyear;
Public int16 wmonth;
Public int16 wdayofweek;
Public int16 wday;
Public int16 whour;
Public int16 wminute;
Public int16 wsecond;
Public int16 wmilliseconds;
}
[Dllimport ("kernel32.dll", charset = charset. ANSI, setlasterror = true, exactspelling = true)]
Private Static extern int32 getsystemtime (ref systemtime stru );
[Dllimport ("kernel32.dll", charset = charset. ANSI, setlasterror = true, exactspelling = true)]
Private Static extern int32 setsystemtime (ref systemtime stru );

Public static void setwindowsclock (datetime DT)
{
// Sets system time. Note: Use UTC time; windows will apply Time Zone

systemtime timestru = default (systemtime);
int32 result = default (int32);

timestru. wyear = (int16) dt. year;
timestru. wmonth = (int16) dt. month;
timestru. wday = (int16) dt. day;
timestru. wdayofweek = (int16) dt. dayofweek;
timestru. whour = (int16) dt. hour;
timestru. wminute = (int16) dt. minute;
timestru. wsecond = (int16) dt. second;
timestru. wmilliseconds = (int16) dt. millisecond;

Result = setsystemtime (ref timestru );

}
}
}

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.