• VC++ 从时间服务器读取时间


     
    /************************************************************************/
    /* 从时间服务器读取时间                                                                     */
    /************************************************************************/
    DWORD GetTimeFromServer(in_addr ipaddr)
    {
     DWORD dwRet = -1;
     SOCKET sSock = socket(AF_INET, SOCK_STREAM, 0);
     struct sockaddr_in sin;
     
     if (sSock != INVALID_SOCKET)
     { 
          memcpy(&sin.sin_addr, &ipaddr, sizeof(in_addr));
          sin.sin_family = AF_INET;
          sin.sin_port   = htons(IPPORT_TIMESERVER);  
       
          //连接服务端
          connect(sSock, (struct sockaddr *)&sin, sizeof(struct sockaddr_in)); 
         for (iRead = 0; iRead < 4; iRead += iResult)
          {
          /*读取时间信息*/
               iResult = recv(sSock, (char*)&dwRet + iRead, 4 - iRead, 0);
               if (iResult < 1)
               {
                    break;
               }
          }
    
          if (iRead == 4)
         {
               dwRet = ntohl(dwRet); 
         }
        else
        {
             ::MessageBox(NULL, "Getting time failed!", "Error", MB_OK | MB_ICONERROR);
        }
     
         closesocket(sSock);
     }  
    
          return dwRet;
    }
     
    -----------------------------------------------------------------------------------------
     
    WSADATA WSAData;
     /*初始化套接字库*/
     if (WSAStartup(MAKEWORD(2, 2), &WSAData) != 0)
     {
      MessageBox("WSAStartup failed.
    ");
      WSACleanup();
      return ;
     }    
    
     in_addr timeServer = {128,138,140,44};          // 时间服务器IP地址
     /*取服务器时间*/
     DWORD dwTime = GetTimeFromServer(timeServer);
     
     if (dwTime != -1)     // 读取时间失败
     {   
          UINT64 uiCurTime, uiBaseTime, uiResult;
         SYSTEMTIME st;
     
         uiBaseTime = ((UINT64) HIGHTIME << 32) + LOWTIME; 
         uiCurTime = (UINT64)dwTime * (UINT64)10000000;
         uiResult = uiBaseTime + uiCurTime;
     
         FileTimeToSystemTime((LPFILETIME)&uiResult, &st);
         CString str = "";
         str.Format("%d-%d-%d", st.wYear, st.wMonth, st.wDay);   // 日期
         AfxMessageBox(str); 
     }
     else
     {
      MessageBox("获取时间失败");
     }
    
     WSACleanup();


  • 相关阅读:
    从零开始在阿里云服务器(Ubuntu)上部署Rails应用
    rspec使用
    ubuntu安装和配置SVN
    给asp:DropDownList追加项到顶层显示
    js生成、删除表格方法
    js验证
    GridView和CheckBox连用,实现全选
    javascript;css;firefox;ie;区别
    回调示例
    GridView联合CheckBox实现全选功能[百度空间搜集]
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13318370.html
Copyright © 2020-2023  润新知