c#获取网络时间并同步本地时间
标签:static byte except files ons wait sys pos uil
通过TCP形式来获取NTP时间。主要代码如下:
[DllImport("kernel32.dll")]
private static extern bool SetLocalTime(ref Systemtime time);
[StructLayout(LayoutKind.Sequential)]
private struct Systemtime
{
public short year;
public short month;
public short dayOfWeek;
public short day;
public short hour;
public short minute;
public short second;
public short milliseconds;
}
///
/// 设置系统时间
///
/// 需要设置的时间
/// 返回系统时间设置状态,true为成功,false为失败
public static bool SetLocalDateTime(DateTime dt)
{
Systemtime st;
st.year = (short)dt.Year;
st.month = (short)dt.Month;
st.dayOfWeek = (short)dt.DayOfWeek;
st.day = (short)dt.Day;
st.hour = (short)dt.Hour;
st.minute = (short)dt.Minute;
st.second = (short)dt.Second;
st.milliseconds = (short)dt.Millisecond;
bool rt = SetLocalTime(ref st);
return rt;
}
public static DateTime GetDateTime(long timeStamp)
{
return new DateTime(1970, 1, 1).AddSeconds(timeStamp).ToLocalTime();
}
public static bool GetInternetTime(string url, out DateTime dt, out string errMsg)
{
dt = DateTime.MinValue;
var startDt = DateTime.Now;
var port = 13;
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) { ReceiveTimeout = 2000 };
try
{
var iphostinfo = Dns.GetHostEntry(url);
var ip = iphostinfo.AddressList[0];
var ipe = new IPEndPoint(ip, port);
var iar = socket.BeginConnect(ipe, null, null);
if (!iar.AsyncWaitHandle.WaitOne(5000))
{
errMsg = "连接超时" + url;
return false;
}
var recvBuffer = new byte[1024];
var sb = new StringBuilder();
var myE = Encoding.UTF8;
int nBytes;
while ((nBytes = socket.Receive(recvBuffer, 0, 1024, SocketFlags.None)) > 0)
{
sb.Append(myE.GetString(recvBuffer, 0, nBytes));
}
var o = sb.ToString().Split(‘ ‘);
TimeSpan ts = DateTime.Now - startDt;
var setDt = Convert.ToDateTime(o[1] + " " + o[2]).Subtract(-ts); // 减去中途消耗的时间
dt = setDt.ToLocalTime();
Console.WriteLine(@"服务器:{0}时间:{1}", url, setDt);
errMsg = "";
return true;
}
catch (Exception ex)
{
errMsg = ex.Message;
return false;
}
finally
{
socket.Close();
}
}
源码如下:
https://files.cnblogs.com/files/lizhijian/%E8%8E%B7%E5%8F%96%E7%BD%91%E7%BB%9C%E6%97%B6%E9%97%B4.rar
感谢阅读
c#获取网络时间并同步本地时间
标签:static byte except files ons wait sys pos uil
原文地址:https://www.cnblogs.com/lizhijian/p/8523373.html
评论