1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
require 'optparse'
require 'socket'
SNTP_MSG = "\010" + "\0" * 47
SNTP_PORT = 123
NTP_UNIX_TIME = 2208988800
set_time = false
opts = OptionParser.new(nil, 15, ' ' * 2) do |opts|
opts.banner = "Usage: #$0 [options] <(S)NTP server>"
opts.separator ''
opts.separator 'Options:'
opts.on('-s', '--set-time', 'Set system time (needs root privileges)') do
set_time = true
end
opts.on_tail('-h', '--help', 'Show this help message') do
puts opts
exit
end
end
begin
opts.parse!
rescue OptionParser::InvalidOption
puts opts
exit
end
unless ARGV[0]
puts opts
exit
end
data = UDPSocket.open do |sd|
sd.send(SNTP_MSG, 0, ARGV[0], SNTP_PORT)
sd.recvfrom(64)[0]
end
data = data.unpack('N12')[10].to_i - NTP_UNIX_TIME
time = Time.at(data)
if set_time
system("date #{time.strftime('%m%d%H%M%Y.%S')}")
else
puts time.asctime
end