public static List <string> GetCurrentConnectedServerInfo() { try { List <string> info = new List <string>(); NtpResponse response = connectedNtpServer.GetTime(); NtpPacket packet = response.Packet; string l1, l2, s1, s2; l1 = packet.OriginateTimestamp.ToString() + ":" + packet.OriginateTimestamp.Microsecond.ToString(); l2 = packet.DestinationTimestamp.ToUniversalTime().ToString() + ":" + packet.OriginateTimestamp.Microsecond.ToString(); s1 = packet.ReceiveTimestamp.ToUniversalTime().ToLongTimeString() + ":" + packet.ReceiveTimestamp.Microsecond; s2 = packet.TransmitTimestamp.ToUniversalTime().ToLongTimeString() + ":" + packet.TransmitTimestamp.Microsecond; info.Add($"Request sent at: {l1} UTC" + $" and received response at {l2} UTC"); info.Add($"Currently connected server ({ServerChooser.FinalServerAddress}) has stratum {packet.Stratum} and runs NTP version {packet.VersionNumber.ToString()}"); info.Add($"Choosed server received our request at {s1} UTC and sent response at {s2} UTC"); return(info); } catch (Exception ex) { MessageBox.Show("An error has occurred, please try to connect again!\n" + "Error message: " + ex.Message); return(new List <string>()); } }
public static string RetrieveSynchronizationInfo() { try { NtpResponse response = NtpConnector.connectedNtpServer.GetTime(); return($"Moved local time by {response.TimeOffset.ToTimeSpan()}"); }catch (Exception ex) { return("Click Synchronize to see more details!"); } }
static void Main(string[] args) { //var udpClient = new UdpClient("ntp1.gatech.edu", 123); //var ipEndpoint = new IPEndPoint(IPAddress.Parse("130.207.165.28"), 123); //var reqBytes = Encoding.ASCII.GetBytes("Anybody there?"); //udpClient.Send(reqBytes, reqBytes.Length); //udpClient.Connect(ipEndpoint); //udpClient.Send(System.Text.Encoding.ASCII.GetBytes(""), 0, ipEndpoint); //var received = udpClient.Receive(ref ipEndpoint); //var rcvString = Convert.ToString(received); var req = new NtpRequest() { LeapIndicator = LeapIndicator.NoLeapSecondAdjustment, Mode = Mode.Client, Stratum = Stratum.PrimaryServer, VersionNumber = 3, OriginateTimestampUtc = DateTime.UtcNow }; var bytes = req.GetBytes(); //const string ntpServer = "ntp2.gatech.edu"; const string ntpServer = "time.windows.com"; var addresses = Dns.GetHostEntry(ntpServer).AddressList; //The UDP port number assigned to NTP is 123 var ipEndPoint = new IPEndPoint(addresses[0], 123); //NTP uses UDP var sw = new Stopwatch(); sw.Start(); using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { socket.Connect(ipEndPoint); //Stops code hang if NTP is blocked socket.ReceiveTimeout = 3000; socket.Send(bytes); socket.Receive(bytes); socket.Close(); } sw.Stop(); var elapsed = sw.ElapsedMilliseconds; var response = NtpResponse.ParseBytes(bytes); }