Get internet time in delphi

2019-04-08 19:38发布

问题:

i want to get time and date from internet

i used following code

IdDayTime1.ReadTimeout := 5000;
IdDayTime1.Host := 'www.time.windows.com';
IdDayTime1.Port := 37     ;
Label1.Caption := IdDayTime1.DayTimeStr;

but i get : socket error # 11004

whats is this and what did i do wrong

my internet and other things are ok

回答1:

DayTime protocol is not the NTP protocol. DayTime uses port 13, not 37. 37 is used by the Time protocol, which, again, in not the NTP protocol, which uses 123 (UDP). I do not know if time.windows.com supports the DayTime and Time protocols, the most common used protocols to get time from a reliable time source nowadays is NTP, and its simpler sibling SNTP, which superseded both DayTime and Time protocols.



回答2:

Socket error 11004 means 'bad address". You need to get rid of the www. prefix, the correct adddress is time.windows.com.



回答3:

Here is some simple code showing the use of the idSNTP components

var
  SNTPClient: TIdSNTP;
begin
  SNTPClient := TIdSNTP.Create(nil);
  try
    SNTPClient.Host := 'pool.ntp.org';
    SNTPClient.SyncTime;
  finally
    SNTPClient.Free;
  end;
end;


回答4:

If you get Time and Date use Indy IdSNTP component and set: host: time.windows.com

and on event Timer1Timer (TTimer component) write:

Label1.Caption := DateToStr(IdSNTP1.DateTime)
   + ' - ' + TimeToStr(IdSNTP1.DateTime);
Label2.Caption := IdSNTP1.Host;

you see on form (labe1, label2) Date now AND Time now. So if you set Time synchronized put IdSNTP1.SyncTime; in event Timer1Timer.



回答5:

Try using the Indy ntp client components with the ntp pool.org servers. Works for me if you have any trouble I will post some example code.