예제 #1
0
        public void Test_Timeout_expires()
        {
            var timeout = TimeSpan.FromMilliseconds(500);

            // Note: pick a host that *drops* packets. The test will fail if the host merely *rejects* packets.
            using (var client = new NtpClient(IPAddress.Parse("8.8.8.8")))
            {
                client.Timeout = timeout;

                var timer = Stopwatch.StartNew();

                try
                {
                    client.GetCorrectionOffset();
                    Assert.Fail("Shouldn't get here. Expecting timeout!");
                }
                catch (SocketException ex) when(ex.ErrorCode == 10060 || ex.ErrorCode == 10035 || ex.ErrorCode == 110)
                {
                    // We expect a socket timeout error
                }

                timer.Stop();

                Assert.IsTrue(timer.Elapsed >= timeout, timer.Elapsed.ToString());
                Assert.IsTrue(timer.Elapsed < timeout + timeout + timeout, timer.Elapsed.ToString());
            }
        }
예제 #2
0
        public void CheckNtpDrift()
        {
            TimeSpan offset;

            using (var ntp = new NtpClient(Dns.GetHostAddresses("pool.ntp.org")[0]))
                offset = ntp.GetCorrectionOffset();

            if (offset.Duration().TotalMilliseconds > NetworkConstants.DefaultNtpDriftThreshold)
            {
                Logger.LogWarning($"NTP clock drift is more that {NetworkConstants.DefaultNtpDriftThreshold} ms : " +
                                  $"{offset.Duration().TotalMilliseconds} ms");
            }
        }
예제 #3
0
        //private static string GenerateConfirmationKey(string secret, long time, string tag)
        //{
        //    var identitySecret = Utilities.BytesFromSecret(secret);

        //    int dataLength = 8;
        //    if(!string.IsNullOrWhiteSpace(tag))
        //    {
        //        if (tag.Length > 32)
        //            dataLength += 32;
        //        else
        //            dataLength += tag.Length;
        //    }

        //    byte[] buff = new byte[dataLength];
        //    int len = 8;
        //    while(true)
        //    {
        //        int newLen = len - 1;
        //        if (len <= 0) break;

        //        buff[newLen] = (byte)time;
        //        time >>= 8;
        //        len = newLen;
        //    }

        //    if(!string.IsNullOrWhiteSpace(tag))
        //        Array.Copy(Encoding.UTF8.GetBytes(tag), 0, buff, 8, dataLength - 8);

        //    try
        //    {
        //        HMACSHA1 hmacGenerator = new HMACSHA1
        //        {
        //            Key = identitySecret
        //        };

        //        byte[] hashedData = hmacGenerator.ComputeHash(buff);
        //        string encodedData = Convert.ToBase64String(hashedData, Base64FormattingOptions.None);
        //        string hash = WebUtility.UrlEncode(encodedData);

        //        return hash;
        //    }
        //    catch(Exception e)
        //    {
        //        throw new Exception($"Unhandled Exception While Generating Confirmation Key => {e}");
        //    }
        //}

        //private static string GenerateConfirmationUrl(string tag = "conf")
        //{
        //    var endpoint = "https://steamcommunity.com" + "/mobileconf/conf?";
        //    var queryStr = GenerateConfirmationKey("cg4LJoNrW2GWOLYIHrgahCWUd3E=", DateTimeOffset.Now.ToUnixTimeMilliseconds(), tag);
        //    return endpoint + queryStr;
        //}

        /// <summary>
        /// Fetches the time from time.windows.com via NTP
        /// </summary>
        /// <returns>
        /// The current time in DateTime format
        /// </returns>
        private static DateTime GetNetworkTime()
        {
            TimeSpan offsetSpan;

            try
            {
                // Initiates the NTP client with the given NTP server and receives correction offsets
                NtpClient ntpClient = new NtpClient(Dns.GetHostAddresses("time.windows.com")[0]);
                offsetSpan = ntpClient.GetCorrectionOffset();
            }
            catch (Exception)
            {
                // The request timed out or the response was not what we expected
                offsetSpan = TimeSpan.Zero;
            }

            return(DateTime.Now + offsetSpan);
        }
예제 #4
0
 //同步NTP时间
 void SyncTime()
 {
     try
     {
         using (var ntp = new NtpClient(Dns.GetHostAddresses(config.NtpServer)[0]))
         {
             var offset = ntp.GetCorrectionOffset();
             state.SystemTimeOffset = offset;
             Logger.Info($"update ntp offset: {offset}");
         }
     }
     catch (Exception ex)
     {
         // timeout or bad SNTP reply
         //state.SystemTimeOffset = TimeSpan.Zero;
         MessageBox.Show($"更新时间失败!\n{ex.Message}");
         Logger.Warn($"更新时间失败! {ex.Message}");
     }
 }
예제 #5
0
        async void Update()
        {
            timeElapsed += Time.deltaTime;
            if (timeElapsed < NtpSpan)
            {
                return;
            }
            timeElapsed = 0;
            TimeSpan tmp;
            bool     isOk = false;
            await Task.Run(() =>
            {
                try
                {
                    NtpClient ntp;
                    ntp  = new NtpClient(Dns.GetHostEntry(Host).AddressList[0], Port);
                    tmp  = ntp.GetCorrectionOffset();
                    isOk = true;
                }
                catch (Exception e)
                {
                    Debug.LogError("Ntp error:" + e.ToString());
                    isOk = false;
                }
            });

            if (!isOk)
            {
                return;
            }
            if (!synced)
            {
                offset = tmp;
                synced = true;
                Debug.Log("NtpTime is started  offset is " + offset.ToString());
                ToastUtil.Toast(this, "NtpTime is started  offset is " + offset.ToString());
            }
            else
            {
                offset = TimeSpan.FromSeconds(0.9 * offset.TotalSeconds + 0.1 * tmp.TotalSeconds);
            }
        }
예제 #6
0
        public void Test_can_get_correction_offset()
        {
            const int tries = 3;
            int       hits  = 0;

            using (var client = new NtpClient(server))
            {
                for (int i = 0; i < tries; i++)
                {
                    try
                    {
                        Console.WriteLine($"Offset #{i + 1}: {client.GetCorrectionOffset()}");
                        ++hits;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Offset #{i + 1}: {ex}");
                    }
                }
            }
            Console.WriteLine($"Got {hits} of {tries} replies");
            Assert.GreaterOrEqual(hits, 1);
        }