C++设置系统时间及系统时间网络更新的方法
时间:2021-05-20 09:28:14|栏目:C代码|点击: 次
本文实例讲述了C++设置系统时间及系统时间网络更新的方法。分享给大家供大家参考。具体实现方法如下:
复制代码 代码如下:
//根据返回的时间设置系统时间
void setTimeFromTP(ULONG ulTime)
{
FILETIME ft;
SYSTEMTIME st;
//将基准时间转换成windows文件时间
st.wYear = 1900;
st.wMonth = 1;
st.wDay = 1;
st.wHour = 0;
st.wMinute = 0;
st.wSecond = 0;
st.wMilliseconds = 0;
SystemTimeToFileTime(&st, &ft);
LONGLONG* pLLong = (LONGLONG*)&ft;
*pLLong += (LONGLONG)10000000*ulTime;
FileTimeToSystemTime(&ft, &st);
::SetSystemTime(&st);
}
void main()
{
CInitSock initSock;
SOCKET s = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s == INVALID_SOCKET)
{
printf("socket error...");
return;
}
sockaddr_in servAddr = {0};
servAddr.sin_family = AF_INET;
servAddr.sin_port = ::htons(37);
servAddr.sin_addr.S_un.S_addr = ::inet_addr("69.25.96.13"); //别用210.72.145.44这个IP, 这是天朝的 常TMD不返回值
if (SOCKET_ERROR == ::connect(s, (sockaddr*)&servAddr, sizeof(servAddr)))
{
printf("connect error..");
return;
}
//接收时间
ULONG ulTime = 0;
int nRecv = ::recv(s, (char*)&ulTime, sizeof(ulTime), 0);
if (nRecv > 0) //收到数据
{
ulTime = ::ntohl(ulTime);
setTimeFromTP(ulTime);
}
else
{
printf("recv error...");
return;
}
::closesocket(s);
printf("*******************************");
getchar();
}
void setTimeFromTP(ULONG ulTime)
{
FILETIME ft;
SYSTEMTIME st;
//将基准时间转换成windows文件时间
st.wYear = 1900;
st.wMonth = 1;
st.wDay = 1;
st.wHour = 0;
st.wMinute = 0;
st.wSecond = 0;
st.wMilliseconds = 0;
SystemTimeToFileTime(&st, &ft);
LONGLONG* pLLong = (LONGLONG*)&ft;
*pLLong += (LONGLONG)10000000*ulTime;
FileTimeToSystemTime(&ft, &st);
::SetSystemTime(&st);
}
void main()
{
CInitSock initSock;
SOCKET s = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s == INVALID_SOCKET)
{
printf("socket error...");
return;
}
sockaddr_in servAddr = {0};
servAddr.sin_family = AF_INET;
servAddr.sin_port = ::htons(37);
servAddr.sin_addr.S_un.S_addr = ::inet_addr("69.25.96.13"); //别用210.72.145.44这个IP, 这是天朝的 常TMD不返回值
if (SOCKET_ERROR == ::connect(s, (sockaddr*)&servAddr, sizeof(servAddr)))
{
printf("connect error..");
return;
}
//接收时间
ULONG ulTime = 0;
int nRecv = ::recv(s, (char*)&ulTime, sizeof(ulTime), 0);
if (nRecv > 0) //收到数据
{
ulTime = ::ntohl(ulTime);
setTimeFromTP(ulTime);
}
else
{
printf("recv error...");
return;
}
::closesocket(s);
printf("*******************************");
getchar();
}
希望本文所述对大家的C++程序设计有所帮助。