看有人发个时间同步的,结果没给源码,就自己捉摸了下,发出来大家共享 ,
13端口是时间服务器的默认端口,通过 这个就可以取得时间了。
首先你要保证可以连接 到时间服务 器,测试方法,在DOS下,用命令 telnet IP 端口号 这样的方式。如果能联通就会弹出一串字符,里面包含有日期和时间信息,取得时间的方法也是这样
下面的代码得到 的时间是世界标准时间,要自己转成本地时间。如果有其他的时间服务器就更好了,。。
中国授权的那个时间服务我这儿网络ping不通,,没法用。。。只有用微软时间同步的服务器了。
// timesync.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <WinSock2.h>
#pragma comment(lib,"Ws2_32.lib")
using namespace std;
int main()
{
WSADATA wsa;
SOCKET sock;
struct sockaddr_in cliaddr;
char buf[100];
char info[9],time[9];
if(WSAStartup(MAKEWORD(2,2), &wsa)==0)
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(sock ==INVALID_SOCKET )
{
cout<<"sock error"<<endl;
exit(0);
}
cliaddr.sin_family=AF_INET;
cliaddr.sin_addr.s_addr = inet_addr("192.43.244.18"); //这个服务器返回的时间是世界标准时间,要自己换成当地时间,北京时间要加8个小时
cliaddr.sin_port = htons(13);
ZeroMemory(buf,100);
ZeroMemory(info,9);
ZeroMemory(time,9);
int a = connect(sock,(sockaddr *)&cliaddr,sizeof(cliaddr));
if(a == SOCKET_ERROR)
exit(0);
recv(sock,buf,100,0);
memcpy(info,&buf[7],8);
memcpy(time,&buf[16],8);
cout<<buf<<endl;
cout<<info<<endl;
cout<<time<<endl;
closesocket(sock);
WSACleanup();
//system("pause");
{
//set the time to windows
SYSTEMTIME st;
char tmp[3];
printf("set time to windows/n");
memset(&st, 0, sizeof(SYSTEMTIME));
tmp[2]='/0';
memcpy(tmp,&info[0],2);
//printf("set time to windows,year=%s/n",tmp);
//printf("set time to windows,year=%d/n",atoi(tmp));
st.wYear = atoi(tmp)+2000; //based on 21th century
memcpy(tmp,&info[3],2);
//printf("set time to windows,month=%s/n",tmp);
//printf("set time to windows,month=%d/n",atoi(tmp));
st.wMonth = atoi(tmp);
memcpy(tmp,&info[6],2);
//printf("set time to windows,day=%s/n",tmp);
//printf("set time to windows,day=%d/n",atoi(tmp));
st.wDay = atoi(tmp);
memcpy(tmp,&time[0],2);
//printf("set time to windows,hour=%s/n",tmp);
//printf("set time to hour,month=%d/n",atoi(tmp));
st.wHour = atoi(tmp)+8;//diff between beijing time and std time
memcpy(tmp,&time[3],2);
//printf("set time to windows,minute=%s/n",tmp);
//printf("set time to minute,month=%d/n",atoi(tmp));
st.wMinute = atoi(tmp);
memcpy(tmp,&time[6],2);
//printf("set time to windows,second=%s/n",tmp);
//printf("set time to second,month=%d/n",atoi(tmp));
st.wSecond = atoi(tmp);
if(!SetLocalTime(&st))
printf("set time to windows fail/n");
else
printf("set time to windows success/n");
}
return 1;
}