#include <iostream>
#include <stdio.h> #include "InitSock.h" using namespace std; void SetTimeFromTP(ULONG ulTime); int main(void)
{
CInitSock initSock;
//创建套接字
SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s == INVALID_SOCKET)
{
cout << "Failed socke()" << endl;
return ;
}
//创建套接字之后如果首先sendto可以不绑定
//若首先recvfrom则需要绑定 //填写远程地址信息
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons();
addr.sin_addr.S_un.S_addr = inet_addr("129.6.15.28 "); //可在http://tf.nist.gov/service/time-servers.html得到IP //连接服务器
if (connect(s, (sockaddr*)&addr, sizeof(addr)) == -)
{
cout << "Failed connect()" << endl;
return ;
} //等待接收时间协议返回的时间,学习Winsock I/O模型后最好使用异步I/O
ULONG ulTime = ;
int nRecv = recv(s, (char*)&ulTime, sizeof(ulTime), );
if (nRecv > )
{
ulTime = ntohl(ulTime);
SetTimeFromTP(ulTime);
cout << "成功与服务器时间同步" << endl;
cout << "接收到的数据: " << ulTime << endl;
}
else
{
cout << "服务器不能确认当前时间" << endl;
} closesocket(s); getchar();
return ;
} void SetTimeFromTP(ULONG ulTime)
{
//Windows文件时间是一个64位的值,是从1601年1月1日中午12:00到现在的时间间隔
//单位是1/1000 0000秒即1000万分之1秒(100-nanosecond)
FILETIME ft;
SYSTEMTIME st;
//首先将基准时间(1900.1.1.0.0.0.0)转换为windows文件时间
st.wYear = ;
st.wMonth = ;
st.wDay = ;
st.wHour = ;
st.wMinute = ;
st.wSecond = ;
st.wMilliseconds = ; SystemTimeToFileTime(&st, &ft);
//然后将Time Protocol使用基准时间加上已经逝去的时间即ulTime
LONGLONG *pLLong = (LONGLONG*)&ft;
//注意文件时间的单位
*pLLong += (LONGLONG) * ulTime;
//再将时间转换回来,更新系统时间
FileTimeToSystemTime(&ft, &st);
//SetSystemTime(&st);
cout << st.wYear << "年"
<< st.wMonth << "月"
<< st.wDay << "日"
<< st.wHour + << "时" //...
<< st.wMinute << "分"
<< st.wSecond << "秒" << endl; }
 
05-08 15:14