Search Unity

Handle Windows time server

Discussion in 'Editor & General Support' started by domdev, Aug 21, 2018.

  1. domdev

    domdev

    Joined:
    Feb 2, 2015
    Posts:
    375
    I this code where I get realtime from time.windows.com..this code I got from forum too
    but sometimes I got error "SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond." and it was from Line 27... any idea how to handle that? I want to call GetNetworkTime(); again if it gives an error

    Code (CSharp):
    1.  
    2. public static DateTime GetNetworkTime()
    3.   {
    4.     //default Windows time server
    5.     const string ntpServer = "time.windows.com";
    6.  
    7.     // NTP message size - 16 bytes of the digest (RFC 2030)
    8.     var ntpData = new byte[48];
    9.  
    10.     //Setting the Leap Indicator, Version Number and Mode values
    11.     ntpData[0] = 0x1B; //LI = 0 (no warning), VN = 3 (IPv4 only), Mode = 3 (Client Mode)
    12.  
    13.     var addresses = Dns.GetHostEntry(ntpServer).AddressList;
    14.  
    15.     //The UDP port number assigned to NTP is 123
    16.     var ipEndPoint = new IPEndPoint(addresses[0], 123);
    17.     //NTP uses UDP
    18.  
    19.     using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
    20.     {
    21.       socket.Connect(ipEndPoint);
    22.  
    23.       //Stops code hang if NTP is blocked
    24.       socket.ReceiveTimeout = 3000;
    25.  
    26.       socket.Send(ntpData);
    27.       socket.Receive(ntpData);
    28.       socket.Close();
    29.     }