Rebex



Sample: TimeGetter

Demonstrates how to connect to the server, get time and NTP/SNTP server info including stratum.

The sample show:

  • Connect SNTP/NTP server.
  • Get server timestamp.
  • Get protocol version supported by the server.
  • Show server stratum.

C#

Ntp ntp = new Ntp(args[0]);

// since we want to know the highest version the server supports, we  
// must declare the highest ourselves (otherwise it would use  
// compatibility mode) 
ntp.VersionNumber = 4;

NtpResponse response = ntp.GetTime();
NtpPacket packet = response.Packet;

Console.WriteLine(
	"We sent the request to the server at {0} UTC and received its response at {1} UTC.", 
	packet.OriginateTimestamp, 
	packet.DestinationTimestamp
);

Console.WriteLine(
	"The server at {0} has stratum {1} and runs NTP version {2}.",
	args[0],
	packet.Stratum,
	packet.VersionNumber
);
	
Console.WriteLine(
	"It received our request at {0} UTC and responded to it at {1} UTC.",
	packet.ReceiveTimestamp,
	packet.TransmitTimestamp
);
	
DateTime current = DateTime.Now;
DateTime exact = current + response.TimeOffset.ToTimeSpan();
Console.WriteLine(
	"The current local time is {0} and it should be adjusted to {1}.", 
	current, 
	exact
);

VB.NET

Dim ntp As Ntp = New Ntp(args(1))

' since we want to know the highest version the server supports, we  
' must declare the highest ourselves (otherwise it would use compatibility mode) 
ntp.VersionNumber = 4

Dim response As NtpResponse = ntp.GetTime()
Dim packet As NtpPacket = response.Packet

Console.WriteLine( _
    "We sent the request to the server at {0} UTC and received its response at {1} UTC.", _
    packet.OriginateTimestamp, _
    packet.DestinationTimestamp _
)

Console.WriteLine( _
    "The server at {0} has stratum {1} and runs NTP version {2}.", _
    args(1), _
    packet.Stratum, _
    packet.VersionNumber _
)

Console.WriteLine( _
    "It received our request at {0} UTC and responded to it at {1} UTC.", _
    packet.ReceiveTimestamp, _
    packet.TransmitTimestamp _
)

Dim current As DateTime = DateTime.Now
Dim exact As DateTime = current.Add(response.TimeOffset.ToTimeSpan)
Console.WriteLine( _
    "The current local time is {0} and it should be adjusted to {1}.", _
    current, _
    exact _
)

See also: