这是一个网络对时的程序
stdafx.h中加上
注意加载相应的Lib库
#pragma comment(lib,"WS2_32");
#include
#include
#pragma once
#include "stdafx.h"
void SetTimeFromTP(ULONG ulTime)
{
FILETIME ft;
SYSTEMTIME st;
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 InitSock()
{
WSADATA wsaData;
DWORD version;
if(WSAStartup(MAKEWORD(2,2),&wsaData))
{
exit(0);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
InitSock();
SOCKET s = ::socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(s == INVALID_SOCKET)
{
printf("Fail to Create Socket!");
return 0;
}
sockaddr_in servAddr;
servAddr.sin_family = AF_INET;
servAddr.sin_port = htons(37);
servAddr.sin_addr.S_un.S_addr = inet_addr("129.6.15.28");
if(::connect(s,(sockaddr *)&servAddr,sizeof(servAddr)) == -1)
{
printf("Fail to Connect!\n");
return 0;
}
ULONG ulTime = 0;
int nRecv = ::recv(s,(char*)&ulTime,sizeof(ulTime),0);
if(nRecv > 0)
{
ulTime = ntohl(ulTime);
SetTimeFromTP(ulTime);
printf("成功和服务器进行了同步!\n");
}
else
{
printf("没有成功和服务器进行了同步!\n");
}
::closesocket(s);
system("pause");
return 0;
}
//加载WinSock库,使用WSAStart函数
//创建一个Socket使用socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
//填写远程地址,相应的sockaddr_in结构
//连接远程服务器:connect(socket,(sockaddr *)&sockaddr_in,sizeof(sockaddr_in));
//接收,相应的RECEIVE函数
阅读(557) | 评论(0) | 转发(0) |