In my application, I encountered a scenario where I needed to enforce a cutoff time for user interactions. However, relying solely on the current system time might not be ideal, especially if users can manipulate their system clocks. To ensure accuracy and prevent manipulation, I decided to consider the date and time from a remote server machine.

In this blog post, I'll look into the process of obtaining the date and time from a remote server in a C# application. We'll explore various approaches and discuss the solutions to accurately retrieve the remote server's date and time. By the end of this post, you'll have a clear understanding of how to integrate remote server time into your application.
 

Querying a remote server for its current time in C#, we typically utilize the Network Time Protocol (NTP) to synchronize the local system time with a remote time server. Here's how we can accomplish this:


        using System;
        using System.Net;
        using System.Net.Sockets;

        public class TimeQuery
        {
            public static DateTime GetRemoteTime(string timeServer)
            {
                // Default time server if not provided
                if (string.IsNullOrEmpty(timeServer))
                {
                    timeServer = "time.windows.com";
                }

                // NTP data format (see RFC 2030)
                byte[] ntpData = new byte[48];
                ntpData[0] = 0x1B;

                // Connect to the time server
                using (var udpClient = new UdpClient(timeServer, 123))
                {
                    udpClient.Send(ntpData, ntpData.Length);
                    ntpData = udpClient.Receive(ref timeServer, 123);
                }

                // Extract the time information from the response
                long intPart = BitConverter.ToInt32(ntpData, 40);
                long fracPart = BitConverter.ToInt32(ntpData, 44);

                long milliseconds = (intPart * 1000) + ((fracPart * 1000) / 0x100000000L);

                // Convert the NTP time to a DateTime object
                DateTime networkDateTime = new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(milliseconds);

                return networkDateTime;
            }

            // Example usage
            public static void Main(string[] args)
            {
                DateTime remoteTime = GetRemoteTime("time.windows.com");
                Console.WriteLine("Remote server time: " + remoteTime);
            }
        }
    

In above code we define a method GetRemoteTime to query a remote server for its current time using the NTP protocol. We send an NTP packet to the specified time server, receive the response, and extract the time information from it and then, we convert the NTP time to a DateTime object representing the remote server's current time.

2

You can explore the option of accessing port 13:


        using System;
        using System.Net.Sockets;

        public class RemoteTime
        {
            public static string GetDaytime(string host)
            {
                try
                {
                    TcpClient tcpClient = new TcpClient(host, 13);
                    NetworkStream networkStream = tcpClient.GetStream();
                    System.IO.StreamReader reader = new System.IO.StreamReader(networkStream);
                    string response = reader.ReadToEnd();
                    reader.Close();
                    tcpClient.Close();
                    return response;
                }
                catch (Exception ex)
                {
                    return "Error: " + ex.Message;
                }
            }

            // Example usage
            public static void Main(string[] args)
            {
                string host = "yourmachineHOST";
                string daytimeResponse = GetDaytime(host);
                Console.WriteLine(daytimeResponse);
            }
        }
    

Above approach provides a straightforward solution, assuming the remote server has port 13 open. However, it's essential to verify whether the port is indeed open before attempting to fetch the daytime. you can be done easily using the telnet command:


        telnet yourmachineHOST 13
    

By checking response, we can confirm the availability of port 13 on the remote server.

3

You can use below code to get server local date & time:


        using System;
        using NTPClient;

        public class RemoteTime
        {
            public static DateTime GetRemoteDateTime(string timeServer)
            {
                // Default time server if not provided
                if (string.IsNullOrEmpty(timeServer))
                {
                    timeServer = "time.windows.com";
                }

                // Create an instance of NtpClient
                NtpClient ntpClient = new NtpClient(timeServer);

                // Query the remote server for its current time
                DateTime remoteDateTime = ntpClient.GetTime();

                return remoteDateTime;
            }

            // Example usage
            public static void Main(string[] args)
            {
                DateTime remoteDateTime = GetRemoteDateTime("time.windows.com");
                Console.WriteLine("Remote server date and time: " + remoteDateTime);
            }
        }
    

Here we define a method GetRemoteDateTime to query the remote server for its current date and time using the NTP protocol. We create an instance of the NtpClient class and specify the time server to connect to. Then, we call the GetTime method to retrieve the remote server's current time.