与计算机同步互联网时间

2023-12-07

所以我制作了一个具有许可证检查功能的程序。该程序仅适用于有限数量的受信任的人(所以我知道他们不会尝试篡改它)

我想要做的是将计算机时钟与互联网时间(例如 time.windows.com 或任何受信任的时间)同步,如果计算机时钟与互联网不匹配,请更改计算机时钟以匹配它。

我知道有 NTP,但 VB.NET 中没有太多项目(我只找到一个源,但它损坏且混乱,尝试修复它,但只是浪费时间)

我还担心它是否可以匹配用户的时区。我想看看我的程序是否可以根据他们的 IP 获取时区,因为我听说 NTP 不支持时区和夏令时。

遇到这种情况有什么好的办法吗?


我最近遇到了 rtc 电池电量低的问题,不得不更新 XP 中的日期和时间。首先我找到了这个类:

Imports System.IO
Imports System.Net
Imports System.Net.Sockets
Imports System.Runtime.InteropServices

Public Class Daytime
    'Internet Time Server class by Alastair Dallas 01/27/04
    'Added a 'ping' trap to query each server before trying to open the stream.  
    'This led to greatly improved speed.
    '  From:                                To:
    '  For Each host In Servers             For Each host In Servers
    '   result = GetNISTTime(host)              If My.Computer.Network.Ping(host) Then
    '   If result > DateTime.MinValue Then          LastHost = host
    '           LastHost = host                     result = GetNISTTime(host)
    '           Exit For                        End If
    '            End If
    '    Next                               Next
    'Since the ping says the server is active I removed the conditional statement 
    'and assigned host to lasthost after a successful ping
    'I also adjusted the 'THRESHOLD_SECONDS' to 3
    'In 'GetNISTTime' I kept getting argument exceptions if 'timestr' was still null after the Try loop
    'so I added this after the Try loop:
    '               If timeStr = "" Then
    '                   Return DateTime.MinValue
    '               End If
    'Also updated server url.
    'Lloyd Folden 01/16/12

    Private Const THRESHOLD_SECONDS As Integer = 3 'Number of seconds
    ' that Windows clock can deviate from NIST and still be okay

    'Server IP addresses from 
    'http://tf.nist.gov/tf-cgi/servers.cgi - current as of 04/16/12
    Private Shared Servers() As String = { _
          "129.6.15.28" _
        , "129.6.15.29" _
        , "132.163.4.101" _
        , "132.163.4.102" _
        , "132.163.4.103" _
        , "128.138.140.44" _
        , "192.43.244.18" _
        , "131.107.1.10" _
        , "66.243.43.21" _
        , "216.200.93.8" _
        , "208.184.49.9" _
        , "207.126.98.204" _
        , "205.188.185.33" _
    }

    Public Shared LastHost As String = ""
    Public Shared LastSysTime As DateTime

    Public Shared Function GetTime() As DateTime
        'Returns UTC/GMT using an NIST server if possible, 
        ' degrading to simply returning the system clock

        'If we are successful in getting NIST time, then
        ' LastHost indicates which server was used and
        ' LastSysTime contains the system time of the call
        ' If LastSysTime is not within 15 seconds of NIST time,
        '  the system clock may need to be reset
        ' If LastHost is "", time is equal to system clock

        Dim host As String
        Dim result As DateTime

        LastHost = ""
        For Each host In Servers
            If My.Computer.Network.Ping(host) Then
                LastHost = host
                result = GetNISTTime(host)
            End If
        Next

        If LastHost = "" Then
            'No server in list was successful so use system time
            result = DateTime.UtcNow()
        End If

        Return result
    End Function

    Public Shared Function SecondsDifference(ByVal dt1 As DateTime, ByVal dt2 As DateTime) As Integer
        Dim span As TimeSpan = dt1.Subtract(dt2)
        Return span.Seconds + (span.Minutes * 60) + (span.Hours * 360)
    End Function

    Public Shared Function WindowsClockIncorrect() As Boolean
        Dim nist As DateTime = GetTime()
        If (Math.Abs(SecondsDifference(nist, LastSysTime)) > THRESHOLD_SECONDS) Then
            Return True
        End If
        Return False
    End Function

    Private Shared Function GetNISTTime(ByVal host As String) As DateTime
        'Returns DateTime.MinValue if host unreachable or does not produce time
        Dim timeStr As String
        Try
            Dim reader As New StreamReader(New TcpClient(host, 13).GetStream)
            LastSysTime = DateTime.UtcNow()
            timeStr = reader.ReadToEnd
            reader.Close()
        Catch ex As SocketException
            'Couldn't connect to server, transmission error
            Debug.WriteLine("Socket Exception [" & host & "]")
            Return DateTime.MinValue
        Catch ex As Exception
            'Some other error, such as Stream under/overflow
            Return DateTime.MinValue
        End Try
        If timeStr = "" Then
            Return DateTime.MinValue
        End If
        'Parse timeStr
        If (timeStr.Substring(38, 9) <> "UTC(NIST)") Then
            'This signature should be there
            Return DateTime.MinValue
        End If
        If (timeStr.Substring(30, 1) <> "0") Then
            'Server reports non-optimum status, time off by as much as 5 seconds
            Return DateTime.MinValue    'Try a different server
        End If

        Dim jd As Integer = Integer.Parse(timeStr.Substring(1, 5))
        Dim yr As Integer = Integer.Parse(timeStr.Substring(7, 2))
        Dim mo As Integer = Integer.Parse(timeStr.Substring(10, 2))
        Dim dy As Integer = Integer.Parse(timeStr.Substring(13, 2))
        Dim hr As Integer = Integer.Parse(timeStr.Substring(16, 2))
        Dim mm As Integer = Integer.Parse(timeStr.Substring(19, 2))
        Dim sc As Integer = Integer.Parse(timeStr.Substring(22, 2))

        If (jd < 15020) Then
            'Date is before 1900
            Return DateTime.MinValue
        End If
        If (jd > 51544) Then yr += 2000 Else yr += 1900

        Return New DateTime(yr, mo, dy, hr, mm, sc)

    End Function

    <StructLayout(LayoutKind.Sequential)> _
        Public Structure SYSTEMTIME
        Public wYear As Int16
        Public wMonth As Int16
        Public wDayOfWeek As Int16
        Public wDay As Int16
        Public wHour As Int16
        Public wMinute As Int16
        Public wSecond As Int16
        Public wMilliseconds As Int16
    End Structure

    Private Declare Function GetSystemTime Lib "kernel32.dll" (ByRef stru As SYSTEMTIME) As Int32
    Private Declare Function SetSystemTime Lib "kernel32.dll" (ByRef stru As SYSTEMTIME) As Int32

    Public Shared Sub SetWindowsClock(ByVal dt As DateTime)
        'Sets system time. Note: Use UTC time; Windows will apply time zone

        Dim timeStru As SYSTEMTIME
        Dim result As Int32

        timeStru.wYear = CType(dt.Year, Int16)
        timeStru.wMonth = CType(dt.Month, Int16)
        timeStru.wDay = CType(dt.Day, Int16)
        timeStru.wDayOfWeek = CType(dt.DayOfWeek, Int16)
        timeStru.wHour = CType(dt.Hour, Int16)
        timeStru.wMinute = CType(dt.Minute, Int16)
        timeStru.wSecond = CType(dt.Second, Int16)
        timeStru.wMilliseconds = CType(dt.Millisecond, Int16)

        result = SetSystemTime(timeStru)

    End Sub
End Class

然后我使用了一个带有多行文本框和 2 个按钮的表单,代码如下:

Public Class Form1
    Dim DateTimeNow As DateTime
    Dim Args(1) As String


    Private Sub btnGetDateTime_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGetDateTime.Click

        DateTimeNow = Daytime.GetTime + DateTimeOffset.Now.Offset
        txtDisplayInfo.AppendText(DateTimeNow.ToString + vbNewLine)

    End Sub

    Private Sub btnSetDateTime_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSetDateTime.Click
        Daytime.SetWindowsClock(Daytime.GetTime)
        txtDisplayInfo.AppendText(DateTime.Now.ToString + vbNewLine)

    End Sub

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Args = Environment.GetCommandLineArgs
        If Args.Last = "-settime" Then
            DateTimeNow = Daytime.GetTime
            If DateTimeNow.ToShortDateString <> DateString Then
                Daytime.SetWindowsClock(Daytime.GetTime)
            End If
            Me.Close()
        End If
    End Sub



End Class

通过 Internet 将 Windows 日期和时间调整为当前日期和时间。由于某种原因 XP 无法正确日期和时间,所以我需要这个直到我可以更换 rtc 电池。你也许可以使用这个。根据我使用的课程的作者的评论。如果您使用 UTC 时间,Windows 将自动调整时区时间。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

与计算机同步互联网时间 的相关文章

随机推荐

  • 如何限制 Spring MVC 控制器的 @RequestMapping 路径中​​的路由扩展?

    我有一个相当简单的任务想要完成 但似乎无法找到有关 Spring MVC 路由的信息 我有一个非常简单的控制器 它将路径路由到视图 Controller RequestMapping value help public class Help
  • SQL Server 2005 db_denydatawriter 示例查询

    我正在尝试将 mydomain myuser 添加到 db denydatawriter 角色 但我可以找到一个简单的查询示例 有人有一个简单的示例吗 如果您还没有设置登录名 用户 只需 3 个步骤 CREATE LOGIN mydomai
  • Bootstrap 元素 100% 宽度

    我想创建交替的 100 彩色块 附件中说明了 理想 情况以及当前情况 所需的设置 现在 我的第一个想法是创建一个 div 类 给它一个背景颜色 并给它 100 的宽度 block width 100 background fff 然而 你可
  • 如何在android中的范围搜索栏中设置两个拇指之间的范围?

    我在我的应用程序中使用范围搜索栏 它工作正常 但我的要求是设置两个拇指之间的范围 默认情况下 两个拇指相互重叠 在我的情况下 拇指不相互重叠 如何设置范围搜索栏中两个拇指之间的范围 下面是我的范围搜索栏类 在我的例子中 两个拇指之间的差异是
  • 从产品获取流会返回一个空集合,其中包含一些动态产品组规则

    我创建了一个装饰 可以自动加载streams对于产品 这使我能够访问店面中的动态产品组 但在使用某些规则时遇到了一些问题 选择特定产品或使用时一切正常productNumber equals number规则 但是当我尝试根据属性值选择产品
  • 灰度背景 CSS 图像

    我在网上搜索了很多 但找不到跨浏览器解决方案来将 css 背景图像淡入灰度并返回 唯一有效的解决方案是应用 CSS3 灰度滤镜 webkit filter grayscale 100 但这仅适用于 Chrome v 15 和 Safari
  • Flutter:语法错误:JSON 中位置 0 处出现意外标记 <

    我需要从 API 获取数据 但我的 try catch 失败并出现 SyntaxError Unexpected token Code String problems try final response await http get ht
  • 在Python中将字符串转换为元组

    好的 我有这个字符串 tc 107 189 我需要它是一个元组 这样我就可以一次将每个数字称为一 print tc 0 needs to output 107 先感谢您 所有你需要的是ast literal eval gt gt gt fr
  • 如何在多个.cpp文件中使用全局变量?

    我有一个简单的程序 它尝试在单独的文件中打印我的全局变量 我正在使用Visual Studio 2013 专业版 IDE print h ifndef PRINT H define PRINT H void Print endif 打印 c
  • ELMAH 异常生成通用“服务不可用”消息

    我正在尝试创建一个可用性页面 该页面检查站点使用的所有服务 将每个检查包装在 try catch 中 然后向用户显示任何失败 其中一项服务是 ELMAH 因此我调用该服务是为了仔细检查我们是否可以成功记录错误 控制器 var a new A
  • 为什么 jquery 自动完成功能在 https(安全页面)上不起作用?

    我试图让 jquery 自动完成功能在 https 安全页面 页面上工作 但它没有显示任何下拉菜单 我搜索了这个问题 发现它的安全问题 谁能告诉我如何在 https 页面上打开此自动完成下拉列表 这是我的 jquery 自动完成代码 fun
  • 使用生成器作为子流程输入;出现“对已关闭文件进行 I/O 操作”异常

    我有一个大文件需要在输入另一个命令之前进行处理 我可以将处理后的数据保存为临时文件 但想避免这样做 我编写了一个生成器 它一次处理每一行 然后按照脚本将其作为输入提供给外部命令 但是我在第二轮循环中遇到了 关闭文件上的 I O 操作 异常
  • Oracle 高级队列 - 出队不起作用

    我似乎找不到解决问题的方法 我已经被困在这个问题上几个小时了 我正在使用 Oracle AQ Dbms Aqadm Create Queue Table Queue Table gt ITEM EVENT QT Queue Payload
  • 即使安装了 Pandas 模块也找不到

    我为此使用 anaconda 我已经使用两者下载了 pandas pip install pandas and conda install pandas 安装成功 再次安装显示已经安装 然而 当单独写这一行时 import pandas a
  • 将更多对象提取到实体中后核心数据关系丢失

    我有一个如下所示的核心数据模型 在表格视图中 我加载了所有约会 上一个UILabel在我里面custom cell我将约会地点名称设置如下 NSString info appointment location label vrij 起初一切
  • 通过将元素与先前元素的累积乘积相乘来创建列

    我有一个向量 df lt c 1000 1 02 1 03 1 04 1 01 我想创建一个新向量 其中包含 df 旧向量 中元素的累积乘积 新列应该看起来像 b lt c 1020 1050 6 1092 64 1103 5 基本上 新向
  • 从另一方收到不安全或不正确安全的故障

    我有一个调用 WCF 服务的 Windows 程序 该服务几次后会变得非常慢 最终会遇到此错误 再次重启后服务再次启动 真挚地 您可能没有关闭与 WCF 服务的连接 WCF 默认有 10 个连接 超时为一分钟 然后发生的事情是前 10 个点
  • 动态更改自动布局

    我必须显示 3 个标签 例如 标签1 标签2 标签3 Horizontally 我想要这 3 个标签的宽度是根据屏幕尺寸宽度均分 如何直接使用 nib 文件实现此目的 Thanks 问题2 标签1 标签2 标签3 所有标签宽度相等 所有La
  • 找不到引用的源:包

    我有这个 pubspec yaml name Dart Pages description The Dart platform dependencies web components any mongo dart any 然后我运行 工具
  • 与计算机同步互联网时间

    所以我制作了一个具有许可证检查功能的程序 该程序仅适用于有限数量的受信任的人 所以我知道他们不会尝试篡改它 我想要做的是将计算机时钟与互联网时间 例如 time windows com 或任何受信任的时间 同步 如果计算机时钟与互联网不匹配