利用RFC868协议编写网络对时程序
2010-06-27 20:41:52 来源:WEB开发网三、网络对时的程序实现
下面是使用TCP协议的实现网络对时的部分代码。GetRemoteTime 函数主要通过连接服务器szSever,并取得其回传的32位值:
BOOL GetRemoteTime(char* szSever, unsigned long& ulTime)
{
SOCKET sock = socket(AF_INET, SOCK_DGRAM, 0); //使用UDP协议
if(sock == INVALID_SOCKET)
{
return FALSE;
}
sockaddr_in severAddr;
severAddr.sin_family = AF_INET;
severAddr.sin_port = htons(NET_TIME_PORT);
severAddr.sin_addr.S_un.S_addr = inet_addr(szSever);
if (sendto(sock, (char*)&ulTime, 4, 0, (sockaddr*)&severAddr, sizeof(severAddr)) == 4)
{
unsigned long flag = 1;
if ((ioctlsocket(sock, FIONBIO, &flag) == 0))
{
struct fd_set mask;
FD_ZERO(&mask);
FD_SET(sock, &mask);
struct timeval timeout;
timeout.tv_sec = TIMEOUT_RECEIVE;
timeout.tv_usec = 0;
if (select(0, &mask, NULL, NULL, &timeout) == 1)
{
if (recv(sock, (char*)&ulTime, 4, 0) == 4)
{
ulTime = ntohl(ulTime);
closesocket(sock);
return TRUE;
}
}
}
}
closesocket(sock);
return FALSE;
}
更多精彩
赞助商链接