- Home /
Problem with GetNetworkTime
public static ulong GetNetworkTime()
{
const string ntpServer = "time.windows.com";
var ntpData = new byte[48];
ntpData[0] = 0x1B;
var addresses = Dns.GetHostEntry(ntpServer).AddressList;
var ipEndPoint = new IPEndPoint(addresses[0], 123);
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
socket.Connect(ipEndPoint);
socket.ReceiveTimeout = 3000;
socket.Send(ntpData);
socket.Receive(ntpData);
socket.Close();
}
const byte serverReplyTime = 40;
ulong intPart = BitConverter.ToUInt32(ntpData, serverReplyTime);
ulong fractPart = BitConverter.ToUInt32(ntpData, serverReplyTime + 4);
intPart = SwapEndianness(intPart);
fractPart = SwapEndianness(fractPart);
var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);
var networkDateTime = (new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc)).AddMilliseconds((long)milliseconds);
return milliseconds;
}
static uint SwapEndianness(ulong x)
{
return (uint)(((x & 0x000000ff) << 24) +
((x & 0x0000ff00) << 8) +
((x & 0x00ff0000) >> 8) +
((x & 0xff000000) >> 24));
}
Android game: Hello, I am using this piece of code to get the internet exact time from Windows servers. It works fine on most devices, but on some it doesnt, it just does nothing. It appear it doesnt work on devices that use ipv6 protocol to connect to the network. I cant replicate the issue because my network uses ipv4. Can anyone help?,
Comment
Your answer
Follow this Question
Related Questions
Online level database 2 Answers
WebClient on Android 0 Answers
Connect to non-unity server with LLAPI 0 Answers
Game server crashes in release and debug build but not in editor (GetThreadContext failed) 0 Answers
Unity Multiplayer Android Game 0 Answers