tags:

views:

640

answers:

3

In C#, how do I query a remote server for its current time?

Similar functionality to

net time \\servername

but returning a datestamp that includes seconds.

Thanks

+3  A: 

You can try getting the daytime on port 13:

System.Net.Sockets.TcpClient t = new System.Net.Sockets.TcpClient ("yourmachineHOST", 13);
System.IO.StreamReader rd = new System.IO.StreamReader (t.GetStream ()); 
Console.WriteLine (rd.ReadToEnd ());
rd.Close();
t.Close();
Zanoni
A nice simple solution, if the remote server has port 13 open...You can test quite simply whether the port is open using telnet yourmachineHOST 13and seeing if you get a response
David Laing
+3  A: 

You can use the NetRemoteTOD function.

An example from http://bytes.com/groups/net-c/246234-netremotetod-usage:

// The pointer.
IntPtr pintBuffer = IntPtr.Zero;

// Get the time of day.
int pintError = NetRemoteTOD(@"\\sony_laptop", ref pintBuffer);

// Get the structure.
TIME_OF_DAY_INFO pobjInfo = (TIME_OF_DAY_INFO)
Marshal.PtrToStructure(pintBuffer, typeof(TIME_OF_DAY_INFO));

// Free the buffer.
NetApiBufferFree(pintBuffer);
Patrick McDonald
+1  A: 

Windows Time Service implements NTP. Here is a C# implementation of an NTP client.

Reed Copsey
If you can't query the actual remote server for its time; you can at least query the same domain controller / NTP server and get a pretty similar time.Using the referenced NTP client is as simple as var client = new InternetTime.SNTPClient("pkh-srv-dc03"); client.Connect(false); Console.WriteLine(client.DestinationTimestamp);
David Laing