public static ParseRawByteArray ( byte array ) : |
||
array | byte | |
return |
public static NtpPacket ReadPacket(UdpClient udpClient, NtpPacket packet) { var remoteEndPoint = new IPEndPoint(IPAddress.Any, 0); byte[] data = null; for (int i = 0; i < 5; i++) { data = packet.ToRawByteArray(); udpClient.Send(data, data.Length); try { data = udpClient.Receive(ref remoteEndPoint); break; } catch (SocketException) { continue; } } if (data == null) { throw new TimeoutException(); } var resultPacket = NtpPacket.ParseRawByteArray(data); return(resultPacket); }
public override void DoRun() { SetTaskState(TaskState.Running); try { progress.SetState(1, "Connecting"); System.Threading.Thread.Sleep(1000); var udpClient = this.CreateUdpClient(); progress.SetState(2, "Connected"); var packet = new NtpPacket(); packet.VersionNumber = 4; packet.Mode = NtpMode.Client; packet.TransmitTimeSpamp = DateTime.Now; var remoteEndPoint = new IPEndPoint(IPAddress.Any, 0); var outdata = packet.ToRawByteArray(); byte[] data = null; for (int i = 0; i < 5; i++) { data = null; progress.SetState(3, $"Requesting Time (Attempt {i + 1})"); udpClient.Send(outdata, outdata.Length); try { data = udpClient.Receive(ref remoteEndPoint); break; } catch (SocketException) { continue; } } var now = DateTime.Now; if (data == null) { throw new TimeoutException(); } var resultPacket = NtpPacket.ParseRawByteArray(data); var localOffset = NtpPacket.CalculateLocalClockOffset(resultPacket, now); value = localOffset; SetTaskState(TaskState.Finished); progress.SetState(4, "Finished"); } finally { if (this.TaskState != TaskState.Finished) { SetTaskState(TaskState.Stopped); progress.SetState(4, "Stopped (Error)"); } } }