这两天有一个应用需要获取网络时间,虽然一直知道可以从时间服务器获取时间,却从来也没有操作过,借这个机会重新进行一下深入了了解。
基本的思路就是:通过SOCKET连接时间服务器,直接接收从服务器发送的过来的时间数据。
void GetNetTime()
{
TIME_ZONE_INFORMATION tzinfo;
DWORD dwStandardDaylight;
int nRet;
/* Initialize Winsock */
WORD wVersionRequested;
WSADATA wsaData;
int nErrCode;
wVersionRequested = MAKEWORD(2, 2);
nErrCode = WSAStartup(wVersionRequested, &wsaData);
if (0 != nErrCode)
{
return;
}
/* Get server IP */
struct hostent *host;
char *pServerIP;
host = gethostbyname("time.nist.gov");
if (NULL == host)
{
return -1;
}
pServerIP = inet_ntoa(*(struct in_addr*)host->h_addr_list[0]);
/* Connect to time server, and get time */
SOCKET sockfd;
char cTimeBuf[40] = { 0 };
unsigned long ulTime = 0;
int nTry &