hoodwink.d enhanced
 

juretta.com

Ruby: Contacting a timeserver | August 26, 2006-->

August 26, 2006
The TIME protocol is an internet protocol defined in http://www.faqs.org/rfcs/rfc868.html
This script shows how to connect to an arbitrary TIME-Server using Ruby's Net::Telnet library.
require 'net/telnet'
TIME_SERVER = 'ntp2.fau.de'

options = {
  "Host" => TIME_SERVER, 
  "Telnetmode" => false, 
  "Timeout" => 30, 
  "Port" => "time"
}

# The time is the number of seconds since 00:00 (midnight) 1 January 1900
# GMT, such that the time 1 is 12:00:01 am on 1 January 1900 GMT; this
# base will serve until the year 2036.
seconds = Net::Telnet.new(options).recv(4).unpack('N').first

# The Ruby Time class handles dates with an epoch 
# starting at midnight january 1 1970
# We have to use the Date class to work with pre-epoch dates.
require 'date'
def get_seconds_diff_1970_1900
  # you might want to cache the Cache result... it won't change ;-)
  (DateTime.new(1970, 1, 1) - DateTime.new(1900, 1, 1)).to_i * 24 * 60 * 60
end

# Convert seconds to a Time object
remote_time = Time.at(seconds - \
  get_seconds_diff_1970_1900).strftime("%Y-%m-%d %H:%M:%S")

print "Time from #{TIME_SERVER} -> #{remote_time}"
  1. http://attachr.com/3911
  2. TIME protocol
  3. www.ntp.org
  4. http://ntp.isc.org/bin/view/Servers/WebHome
  5. Wikipedia: Network Time Protocol
  6. Net::Telnet
  7. RFC 958
  8. Ruby Date

Kudos to Peter Cooper who pointed out that we are using the TIME protocol (TCP on port 37) not NTP on UDP port 123!

@17:20 | Comments: 1

Diggman

Related Entries


1
Peter Cooper says:
Avatar Thu Nov 02 01:35:27 +0100 2006 | #

That’s the TIME protocol, not NTP. NTP is UDP on port 123 and a lot more complex.

About

juretta.com is the personal workspace of Stefan Saasen. You can send him an email or read more about this site in the „About“ section.

« Previous entry

Profiling Your Applications with Ecli...
posted over 2 years ago

» Next entry

Ruby 1.8.5 Released
posted over 2 years ago

Related Entries

Recent comment

On: “Attachr.com: OpenID support added

You need to kill this spam stuff!

posted about 1 year ago by entropie

Look!

Latest links  RSS  

More...