Synchronize Your System Clock to an Atomic Clock

This sample illustrates how to use the Winsock control and the SetSystemTime API to set your system's clock to the time reported by one of many Network Time Protocol (NTP) servers.

Synchronize your computer's clock with a NTP server.
Download Source Code

Submitted By

This sample was submitted by EM. You can reach EM at webmaster@em.f2s.com.

Discussion

The Winsock control provides access to TCP network services without knowing the details of TCP or how to call low level Winsock APIs. By setting the control's properties and calling its methods, you can connect to a remote machine and exchange data in both directions.

This app acts as a client thus it needs to set the server computer's name or IP address and port on which it will be listening. The computer's name is set by setting the control's RemoteHost property to the URL selected in the dropdown. The server's port is set by assigning 37, the NTP server's port, to the RemotePort property.

The Connect method is then called to establish the connection. Once a connection is established, either computer can send or receive data. To send data, call the SendData method. Whenever data is received, the DataArrival event occurs. Call the GetData method within the DataArrival event to retrieve the data.

Conversely, when creating a server application, set a port, via the LocalPort property, on which to listen and invoke the Listen method. When the client computer requests a connection, the ConnectionRequest event fires. To complete the connection, call the Accept method within the ConnectionRequest event.

When a connection is established the control's Connect event fires. Here, the VB Timer command is used to return the number of seconds since midnight. In the DataArrival event, the control's Getdata method is called to retrieve a 32 bit timestamp from the NTP server.

When the server is done transmitting data, the control's Close event fires. This event is used to call the control's Close method to close the TCP connection. Also, the Timer command is used to get the current time again. Using the two time values the round trip latency to the server can be determined and subsequently used to adjust the time value.

A routine is called to adjust the server's time by the latency factor and convert it into a SYSTEMTIME structure which is used by the SetSystemTime API to update the PC's clock.

Instructions

Download the source code and press F5 to run the program. Change your system's time. Select a server to synchronize with and click the "Sync" button. The clock may not display the refreshed time until the next minute change.




About TheScarms
About TheScarms


Sample code
version info

If you use this code, please mention "www.TheScarms.com"

Email this page


© Copyright 2024 TheScarms
Goto top of page