Click here to Skip to main content
15,860,859 members
Articles / Programming Languages / C#

Connecting To A Network Time Server

Rate me:
Please Sign up or sign in to vote.
2.92/5 (10 votes)
11 Jul 2008CPOL1 min read 66.8K   1.5K   30   11
This simple article explains how to connect to a network time server

Introduction

This article is a very simple introduction to the Network Time Protocol. It explains briefly how you can synchronize your applications with a time from a Network Time Server. NTP provides a reliable way of synchronizing time on IT networks. NTP is present on virtually all computers and allows systems to synchronize their clocks with a time source over the TCP/IP networks.

On a Windows operating system, you can synchronize your system clock with time.windows.com. Alternatively you can enter a Network Time Server of your choice.

There are Network Time Servers all around the world, some are publicly accessible and are mainly setup in university institutions. Network Time Servers are mainly over UDP listening on port 123. Microsoft's Internet Time server time.windows.com uses UDP on port 123.

The following code connects to www.pogostick.net on port 13. This Network Time Server uses TCP. The server is located in Norway.

C#
try 
{ 
    TcpClient NTS = new TcpClient("www.pogostick.net", 13); 

    if (NTS.Connected) 
    { 
        //Connected 
    } 

} 
catch (Exception E) 
{ 
    //Not Connected 
}

Once connected to the Network Time Server, the server will respond with the date and time. The following code sets up a NetworkStream and a StreamReader to read data from the server.

C#
NetworkStream ns = NTS.GetStream(); 
StreamReader sr = new StreamReader(ns); 
string Response = sr.ReadLine();

The server will respond with a message like the following:

"text"
Sun Mar 3 22:04:24 2007

We can extract the time from the response by using the split method. The following code splits the response from the server and stores the data into an array variable.

C#
static void ProcessResponse() 
{ 
    string[] splitRes = Response.Split(' '); 
    strDate = splitRes[0]; 
    strMonth = splitRes[1]; 
    intDate = int.Parse(splitRes[3]); 
    strTime = splitRes[4]; 
    strYear = splitRes[5]; 
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Bugit seems this code is KO Pin
Member 1478579629-Mar-20 7:25
Member 1478579629-Mar-20 7:25 
Questionsalam Pin
arastoooo5-Sep-11 13:15
arastoooo5-Sep-11 13:15 
GeneralAlternative approach Pin
djlove14-Jul-08 22:19
djlove14-Jul-08 22:19 
GeneralI updated your TimeServer code Pin
Paw Jershauge23-Sep-07 22:40
Paw Jershauge23-Sep-07 22:40 
Replace the code in the NTServer.cs file with this
<br />
<font color="black"><br />
<font color="blue">using</font> System;<br />
<font color="blue">using</font> System.Globalization;<br />
<font color="blue">using</font> System.Net.Sockets;<br />
<font color="blue">using</font> System.Net;<br />
<font color="blue">using</font> System.IO;<br />
<br />
<font color="blue">public</font> <font color="blue">class</font> TimeServer<br />
    {<br />
    <font color="blue">private</font> <font color="#408080">TcpClient</font> NTS;<br />
    <font color="blue">private</font> <font color="#408080">NetworkStream</font> ns;<br />
    <font color="blue">private</font> <font color="#408080">StreamReader</font> sr;<br />
    <font color="blue">private</font> <font color="#408080">DateTime</font> srvdate;<br />
    <font color="blue">private</font> <font color="blue">string</font> srvUrl;<br />
    <font color="blue">private</font> <font color="blue">int</font> srvPort;<br />
    <font color="blue">private</font> <font color="blue">string</font> srvTimeFormat;<br />
    <font color="blue">private</font> <font color="#408080">CultureInfo</font> srv<font color="#408080">CultureInfo</font>;<br />
    <font color="blue">private</font> <font color="blue">bool</font> _success = <font color="blue">false</font>;<br />
<br />
    <font color="blue">public</font> TimeServer(<font color="blue">string</font> TimeServerUrl)<br />
    {<br />
        srvUrl = TimeServerUrl;<br />
        srvPort = 13;<br />
        srvTimeFormat = "yyyy-MM-dd HH:mm:ss";<br />
        srv<font color="#408080">CultureInfo</font> = <font color="#408080">CultureInfo</font>.InvariantCulture;<br />
        GetTime();<br />
    }<br />
    <font color="blue">public</font> TimeServer(<font color="blue">string</font> TimeServerUrl, <font color="blue">int</font> port)<br />
    {<br />
        srvUrl = TimeServerUrl;<br />
        srvPort = port;<br />
        srvTimeFormat = "yyyy-MM-dd HH:mm:ss";<br />
        srv<font color="#408080">CultureInfo</font> = <font color="#408080">CultureInfo</font>.InvariantCulture;<br />
        GetTime();<br />
    }<br />
    <font color="blue">public</font> TimeServer(<font color="blue">string</font> TimeServerUrl, <font color="blue">int</font> port, <font color="blue">string</font> Timeformat)<br />
    {<br />
        srvUrl = TimeServerUrl;<br />
        srvPort = port;<br />
        srvTimeFormat = Timeformat;<br />
        srv<font color="#408080">CultureInfo</font> = <font color="#408080">CultureInfo</font>.InvariantCulture;<br />
        GetTime();<br />
    }<br />
    <font color="blue">public</font> TimeServer(<font color="blue">string</font> TimeServerUrl, <font color="blue">int</font> port, <font color="blue">string</font> Timeformat, <font color="#408080">CultureInfo</font> Cultureinfo)<br />
    {<br />
        srvUrl = TimeServerUrl;<br />
        srvPort = port;<br />
        srvTimeFormat = Timeformat;<br />
        srv<font color="#408080">CultureInfo</font> = Cultureinfo;<br />
        GetTime();<br />
    }<br />
<br />
    <font color="blue">public</font> <font color="#408080">DateTime</font> Server<font color="#408080">DateTime</font><br />
    {<br />
        get<br />
        {<br />
            return srvdate;<br />
        }<br />
    }<br />
<br />
    <font color="blue">public</font> <font color="blue">bool</font> Success<br />
    {<br />
        get<br />
        {<br />
            return _success;<br />
        }<br />
    }<br />
<br />
    <font color="blue">public</font> void GetTime()<br />
    { <br />
        try<br />
        {<br />
            if (srvUrl != "" && srvPort > 0)<br />
            {<br />
                NTS = new <font color="#408080">TcpClient</font>(srvUrl, srvPort);<br />
                if (NTS.Connected)<br />
                {<br />
                    <font color="blue">string</font> srvresponse = "";<br />
                    ns = NTS.GetStream();<br />
                    sr = new <font color="#408080">StreamReader</font>(ns);<br />
                    srvresponse = sr.ReadLine();<br />
                    try<br />
                    {<br />
                        srvdate = <font color="#408080">DateTime</font>.ParseExact(srvresponse.Trim(), srvTimeFormat, srv<font color="#408080">CultureInfo</font>);<br />
                        _success = <font color="blue">true</font>;<br />
                    }<br />
                    catch { _success = <font color="blue">false</font>; throw; }<br />
                }<br />
            }<br />
        }<br />
        catch { _success = <font color="blue">false</font>; throw; }    <br />
    }<br />
}<br />
</font>


And this in the static void Main of the NetworkTimeServer.cs file:

try<br />
            {<br />
                TimeServer Ts = new TimeServer("www.pogostick.net", 13, "ddd MMM d HH:mm:ss yyyy");<br />
                if (Ts.Success)<br />
                {<br />
                    Console.WriteLine("ToLongDateString: " + Ts.ServerDateTime.ToLongDateString());<br />
                    Console.WriteLine("DateTime.ToString: " + Ts.ServerDateTime.ToString());<br />
                    Console.WriteLine("Year: " + Ts.ServerDateTime.Year);<br />
                    Console.WriteLine("Month: " + Ts.ServerDateTime.Month);<br />
                    Console.WriteLine("Day: " + Ts.ServerDateTime.Day);<br />
                    Console.WriteLine("Hour: " + Ts.ServerDateTime.Hour);<br />
                    Console.WriteLine("Minute: " + Ts.ServerDateTime.Minute);<br />
                    Console.WriteLine("Second: " + Ts.ServerDateTime.Second);<br />
                    Console.WriteLine("DayOfWeek: " + Ts.ServerDateTime.DayOfWeek);<br />
                    Console.WriteLine("DayOfYear: " + Ts.ServerDateTime.DayOfYear);<br />
                    Console.WriteLine("------------------------------------------");<br />
                }<br />
                Ts.GetTime();<br />
                if (Ts.Success)<br />
                {<br />
                    Console.WriteLine("ToLongDateString: " + Ts.ServerDateTime.ToLongDateString());<br />
                    Console.WriteLine("DateTime.ToString: " + Ts.ServerDateTime.ToString());<br />
                    Console.WriteLine("Year: " + Ts.ServerDateTime.Year);<br />
                    Console.WriteLine("Month: " + Ts.ServerDateTime.Month);<br />
                    Console.WriteLine("Day: " + Ts.ServerDateTime.Day);<br />
                    Console.WriteLine("Hour: " + Ts.ServerDateTime.Hour);<br />
                    Console.WriteLine("Minute: " + Ts.ServerDateTime.Minute);<br />
                    Console.WriteLine("Second: " + Ts.ServerDateTime.Second);<br />
                    Console.WriteLine("DayOfWeek: " + Ts.ServerDateTime.DayOfWeek);<br />
                    Console.WriteLine("DayOfYear: " + Ts.ServerDateTime.DayOfYear);<br />
                }<br />
            }<br />
            catch (Exception e)<br />
            {<br />
                Console.Write(e.Message);<br />
            }<br />
            Console.Read();


This will give your code more flexibility, hope you can use it... Big Grin | :-D Big Grin | :-D
GeneralRe: I updated your TimeServer code Pin
Lechuss24-Sep-07 21:19
Lechuss24-Sep-07 21:19 
GeneralRe: I updated your TimeServer code Pin
cspinelive4-Aug-08 10:42
cspinelive4-Aug-08 10:42 
GeneralMinor error Pin
sadavoya5-Mar-07 4:04
sadavoya5-Mar-07 4:04 
GeneralRe: Minor error Pin
Syed M Hussain5-Mar-07 4:55
Syed M Hussain5-Mar-07 4:55 
GeneralRe: Minor error Pin
sadavoya5-Mar-07 4:57
sadavoya5-Mar-07 4:57 
QuestionWhy don't use DateTime.Parse? Pin
Christian Klauser4-Mar-07 8:54
Christian Klauser4-Mar-07 8:54 
AnswerRe: Why don't use DateTime.Parse? PinPopular
Paw Jershauge23-Sep-07 22:25
Paw Jershauge23-Sep-07 22:25 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.