title: Basic NTP Client in Windows in Visual C++
body: <p>Good day,</p>
  
  <p>I am attempting to implement a very basic NTP client just so I can query a remote NTP server (ie: <code>pool.ntp.org</code>) for the internet time to automatically set the time on my Windows development board on each boot.</p>
  
  <p>I've refactored the code here from another user:</p>
  
  <p><a href="https://stackoverflow.com/questions/13011532/get-time-date-from-server-with-sntpwindows-c">Get time/date from server with sntp(windows c++)</a></p>
  
  <p>But the program hangs at the <code>recv()</code> operation. The DNS resolution and <code>send()</code> operations appear to execute without any issues.</p>
  
  <p>Does anyone know where I can find a simple NTP client example in Windows (GPL is preferred, but anything would do at this point), or can they comment on why the following code block would hang from the example (I shouldn't say "hang", it just never appears to receive a response).</p>
  
  <p><strong>NTP_CLIENT.CPP</strong></p>
  
  <pre><code>/******************************************************************************
   * Project Headers
   *****************************************************************************/
  #include "stdafx.h"
  #include "ntp_client.h"
  
  /******************************************************************************
   * System Headers
   *****************************************************************************/
  #include &lt;winsock2.h&gt;
  #include &lt;winsock.h&gt;
  #include &lt;ws2tcpip.h&gt;
  
  
  /******************************************************************************
   * Preprocessor Directives and Macros
   *****************************************************************************/
  
  
  /******************************************************************************
   * Class Member Function Definitions
   *****************************************************************************/
  void Timestamp::ReverseEndian(void) {
      ReverseEndianInt(seconds);
      ReverseEndianInt(fraction);
  }
  
  time_t Timestamp::to_time_t(void) {
      return (seconds - ((70 * 365 + 17) * 86400))&amp;0x7fffffff;
  }
  
  void NTPMessage::ReverseEndian(void) {
      ref.ReverseEndian();
      orig.ReverseEndian();
      rx.ReverseEndian();
      tx.ReverseEndian();
  }
  
  int NTPMessage::recv(int sock) {
      int ret = ::recv(sock, (char*)this, sizeof(*this), 0);
      ReverseEndian();
      return ret;
  }
  
  int NTPMessage::sendto(int sock, struct sockaddr_in* srv_addr) {
      ReverseEndian();
      int ret = ::sendto(sock, (const char*)this, sizeof(*this), 0, (sockaddr*)srv_addr, sizeof(*srv_addr));
      ReverseEndian();
      return ret;
  }
  
  void NTPMessage::clear() {
      memset(this, 0, sizeof(*this));
  }
  </code></pre>
  
  <p><strong>NTP_CLIENT.H</strong></p>
  
  <pre><code>#ifndef __NTP_CLIENT_H__
  #define __NTP_CLIENT_H__
  
  #include &lt;ctime&gt;
  
  #define ReverseEndianInt(x) ((x) = \
      ((x)&amp;0xff000000) &gt;&gt; 24 |       \
      ((x)&amp;0x00ff0000) &gt;&gt; 8  |       \
      ((x)&amp;0x0000ff00) &lt;&lt; 8  |       \
      ((x)&amp;0x000000ff) &lt;&lt; 24)
  
  /**
   * NTP Fixed-Point Timestamp Format.
   * From [RFC 5905](http://tools.ietf.org/html/rfc5905).
   */
  struct Timestamp {
      unsigned int seconds;   /**&lt; Seconds since Jan 1, 1900. */
      unsigned int fraction;  /**&lt; Fractional part of seconds. Integer number of 2^-32 seconds. */
  
      /**
       * Reverses the Endianness of the timestamp.
       * Network byte order is big endian, so it needs to be switched before
       * sending or reading.
       */
      void ReverseEndian(void);
  
      /**
       * Convert to time_t.
       * Returns the integer part of the timestamp in unix time_t format,
       * which is seconds since Jan 1, 1970.
       */
      time_t to_time_t(void);
  };
  
  /**
   * A Network Time Protocol Message.
   * From [RFC 5905](http://tools.ietf.org/html/rfc5905).
   */
  struct NTPMessage {
      unsigned int mode :3;           /**&lt; Mode of the message sender. 3 = Client, 4 = Server */
      unsigned int version :2;        /**&lt; Protocol version. Should be set to 3. */
      unsigned int leap :2;           /**&lt; Leap seconds warning. See the [RFC](http://tools.ietf.org/html/rfc5905#section-7.3) */
      unsigned char stratum;          /**&lt; Servers between client and physical timekeeper. 1 = Server is Connected to Physical Source. 0 = Unknown. */
      unsigned char poll;             /**&lt; Max Poll Rate. In log2 seconds. */
      unsigned char precision;        /**&lt; Precision of the clock. In log2 seconds. */
      unsigned int sync_distance;     /**&lt; Round-trip to reference clock. NTP Short Format. */
      unsigned int drift_rate;        /**&lt; Dispersion to reference clock. NTP Short Format. */
      unsigned char ref_clock_id[4];  /**&lt; Reference ID. For Stratum 1 devices, a 4-byte string. For other devices, 4-byte IP address. */
      Timestamp ref;                  /**&lt; Reference Timestamp. The time when the system clock was last updated. */
      Timestamp orig;                 /**&lt; Origin Timestamp. Send time of the request. Copied from the request. */
      Timestamp rx;                   /**&lt; Recieve Timestamp. Reciept time of the request. */
      Timestamp tx;                   /**&lt; Transmit Timestamp. Send time of the response. If only a single time is needed, use this one. */
  
  
      /**
       * Reverses the Endianness of all the timestamps.
       * Network byte order is big endian, so they need to be switched before
       * sending and after reading.
       *
       * Maintaining them in little endian makes them easier to work with
       * locally, though.
       */
      void ReverseEndian(void);
  
      /**
       * Recieve an NTPMessage.
       * Overwrites this object with values from the received packet.
       */
      int recv(int sock);
  
      /**
       * Send an NTPMessage.
       */
      int sendto(int sock, struct sockaddr_in* srv_addr);
  
      /**
       * Zero all the values.
       */
      void clear();
  };
  
  #endif  /* __NTP_CLIENT_H__ */
  </code></pre>
  
  <p>Firewall and antivirus software has been disabled on the device under test.</p>
  
  <p>Thank you.</p>
  
  <p><strong>EDIT</strong></p>
  
  <hr>
  
  <p>As requested, this is the body of <code>main</code>:</p>
  
  <pre><code>WSADATA wsaData;
  DWORD ret = WSAStartup(MAKEWORD(2,0), &amp;wsaData);
  
  char *host = "pool.ntp.org"; /* Don't distribute stuff pointing here, it's not polite. */
  //char *host = "time.nist.gov"; /* This one's probably ok, but can get grumpy about request rates during debugging. */
  
  NTPMessage msg;
  /* Important, if you don't set the version/mode, the server will ignore you. */
  msg.clear();
  msg.version = 3;
  msg.mode = 3 /* client */;
  
  NTPMessage response;
  response.clear();
  
  int sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
  sockaddr_in srv_addr;
  memset(&amp;srv_addr, 0, sizeof(srv_addr));
  dns_lookup(host, &amp;srv_addr); /* Helper function defined below. */
  
  msg.sendto(sock, &amp;srv_addr);
  response.recv(sock);
  
  time_t t = response.tx.to_time_t();
  char *s = ctime(&amp;t);
  printf("The time is %s.", s);
  
  WSACleanup();
  </code></pre>
  
  <hr>
  
  <p><strong>References</strong></p>
  
  <ol>
  <li><a href="https://stackoverflow.com/questions/13011532/get-time-date-from-server-with-sntpwindows-c">Get time/date from server with sntp(windows c++)</a></li>
  </ol>