向页面发送http请求获取服务器时间

向页面发送http请求获取服务器时间

BOOL BjcaFunc::GetNetTime(string &year, string &month, string &day)   
{ 
    WSADATA WSAData;  
    ::WSAStartup (MAKEWORD(2,2), &WSAData);  
    SOCKET sockeId;  
    SOCKADDR_IN addr;  //IPPROTO_TCP
    if (-1 == (sockeId = socket(AF_INET, SOCK_STREAM, 0)))
        return FALSE;

    hostent *pht = gethostbyname("www.360.cn");
    if(pht == NULL){
        return false;
    }
    char pstr[20] = {0};
    sprintf(pstr,"%d.%d.%d.%d",(pht->h_addr_list[0][0]&0x00ff),(pht->h_addr_list[0][1]&0x00ff),(pht->h_addr_list[0][2]&0x00ff),(pht->h_addr_list[0][3]&0x00ff));
    addr.sin_addr.S_un.S_addr = inet_addr(pstr); //域名转IP

    addr.sin_family = AF_INET;
    addr.sin_port = htons(80);	
    if (SOCKET_ERROR == connect(sockeId, (SOCKADDR * )&addr, sizeof(addr))){
        closesocket(sockeId);
        WSACleanup();
        return FALSE;
    }
    char Timehead[] =  "HEAD / HTTP/1.1\r\nhost: www.360.cn\r\nConnection: Close\r\n\r\n";
    if (SOCKET_ERROR == send(sockeId, Timehead, strlen(Timehead), 0)){
        closesocket(sockeId);
        WSACleanup();
        return FALSE;
   }
   char recvInfo[BUFFSIZE_H];
   ZeroMemory(recvInfo,BUFFSIZE_H);
   recv(sockeId, recvInfo, BUFFSIZE_H, 0);
   closesocket(sockeId);
   WSACleanup();    //recvInfo就是返回的请求信息,解析字符串得到时间 
   std::vector retStr;
   SplitString(string(recvInfo), "\r\n", retStr);    //拆分字符串,"Date:"后面就是时间
   std::vector retStrTime;
   SplitString(retStr[1], " ", retStrTime);
   day = retStrTime[2];
   month = retStrTime[3];
   year = retStrTime[4];
   return TRUE;
}

从拆分后的字符串中取出时间。

向页面发送http请求获取服务器时间_第1张图片

你可能感兴趣的:(C/C++)