Reputation: 3152
I'm trying to get outside server's time.
First, I tried that:
string URL = "http://google.com";
System.Net.HttpWebRequest rq2 = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(URL);
System.Net.HttpWebResponse res2 = (System.Net.HttpWebResponse)rq2.GetResponse();
DateTime xd = rq2.Date;
But this was slow, and do not contain milliseconds.
Then I've found out, that I could actually get server's time from ntp server that is used by target server.
InternetTime.SNTPClient sntp = new InternetTime.SNTPClient("time-b.timefreq.bldrdoc.gov");
sntp.Connect(false); // true to update local client clock
DateTime dt = sntp.DestinationTimestamp.AddMilliseconds(sntp.LocalClockOffset);
string timeStampNow = dt.ToString("dd/MM/yyyy HH:mm:ss.fff");
It works pretty well, however, I'm not sure whether my target server uses ntp server and if it does, I don't know how to find it. I've spent a lot time on researches so I've decided to ask in here.
edit2: I do not have any access to that server (besides visiting it's www page), I do know, that the server is using Microsoft-IIS/7.5 web server.
Upvotes: 4
Views: 1939
Reputation: 134125
There is no way to reliably get a random HTTP server's time with more resolution than what it returns in the response header. That, as you've found, is accurate only to seconds. And it's not the current time, but rather the time that the server populated the header. You don't know if it's the time that the request came in, the time that the response was sent, or possibly some random time that some goofy programmer stuffed into the header just to make your life difficult. All you can say is, "this is the time the server reported."
Even if you knew what NTP server the server in question gets its time from, and assuming that you could access that server, getting time from it won't give you an accurate value for the server's time. Servers update their clocks via NTP periodically, but that might be daily, weekly, monthly, or "whenever the admin decides to." The NTP server's time will not accurately reflect the particular server's time. Certainly not in the milliseconds range, in the general case. And possibly not even within minutes if the server hasn't synchronized its clock with the NTP server in some time.
By the way, if all you're looking for is the time that the server returns, you probably should do a HEAD request if possible. But you have to support doing a GET request as well, because many servers will return a 405 error in response to a HEAD request.
Upvotes: 3