title: C# Universal Windows Application How to get time from internet
body: <p>I'm having trouble with the Raspberry Pi 3 running Windows 10 IoT core as the system clock tends to drift quite significantly over time. I decided to make a program, which would set the system clock back into correct time, which the device would acquire from the internet. I already know how I can set the system clock, but the problem is: How do I acquire precise time from the internet when running C# Universal Windows Application on Windows 10 IoT core?</p>
  
  <p>I have done the following before to acquire time from windows time server on x86 and x64:</p>
  
  <pre><code>public static DateTime GetNetworkTime()
  {
      //default Windows time server
      const string ntpServer = "time.windows.com";
  
      // NTP message size - 16 bytes of the digest (RFC 2030)
      var ntpData = new byte[48];
  
      //Setting the Leap Indicator, Version Number and Mode values
      ntpData[0] = 0x1B; //LI = 0 (no warning), VN = 3 (IPv4 only), Mode = 3 (Client Mode)
  
      var addresses = Dns.GetHostEntry(ntpServer).AddressList;
  
      //The UDP port number assigned to NTP is 123
      var ipEndPoint = new IPEndPoint(addresses[0], 123);
      //NTP uses UDP
      var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  
      socket.Connect(ipEndPoint);
  
     //Stops code hang if NTP is blocked
     socket.ReceiveTimeout = 3000;     
  
     socket.Send(ntpData);
     socket.Receive(ntpData);
     socket.Close();
  
     //Offset to get to the "Transmit Timestamp" field (time at which the reply 
    //departed the server for the client, in 64-bit timestamp format."
    const byte serverReplyTime = 40;
  
    //Get the seconds part
    ulong intPart = BitConverter.ToUInt32(ntpData, serverReplyTime);
  
    //Get the seconds fraction
    ulong fractPart = BitConverter.ToUInt32(ntpData, serverReplyTime + 4);
  
    //Convert From big-endian to little-endian
    intPart = SwapEndianness(intPart);
    fractPart = SwapEndianness(fractPart);
  
    var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);
  
    //**UTC** time
    var networkDateTime = (new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc)).AddMilliseconds((long)milliseconds);
  
    return networkDateTime.ToLocalTime();
  }
  
  // stackoverflow.com/a/3294698/162671
  static uint SwapEndianness(ulong x)
  {
      return (uint) (((x &amp; 0x000000ff) &lt;&lt; 24) +
                 ((x &amp; 0x0000ff00) &lt;&lt; 8) +
                 ((x &amp; 0x00ff0000) &gt;&gt; 8) +
                 ((x &amp; 0xff000000) &gt;&gt; 24));
  }
  </code></pre>
  
  <p>but it does not work for universal windows applications, as <code>Dns</code> and other related classes are not available for use.</p>