Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the exact time for a remote server

Tags:

c#

.net

time

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

like image 834
David Laing Avatar asked Jun 17 '09 16:06

David Laing


People also ask

How do I get time from another server?

You can use NTP protocol to retrieve datetime from a remote server.


2 Answers

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);
like image 143
Patrick McDonald Avatar answered Sep 21 '22 18:09

Patrick McDonald


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();
like image 43
Zanoni Avatar answered Sep 22 '22 18:09

Zanoni