Ejemplo n.º 1
0
bool GetMyExternalIP2(const CService& addrConnect, const char* pszGet, const char* pszKeyword, CNetAddr& ipRet)
{
  SOCKET hSocket;
  if(!ConnectSocket(addrConnect, hSocket))
    return error("GetMyExternalIP() : connection to %s failed", addrConnect.ToString().c_str());

  send(hSocket, pszGet, strlen(pszGet), MSG_NOSIGNAL);

  string strLine;
  while(RecvLine(hSocket, strLine))
  {
    if(strLine.empty()) // HTTP response is separated from headers by blank line
    {
      loop
      {
        if(!RecvLine(hSocket, strLine))
        {
          closesocket(hSocket);
          return false;
        }
        if(pszKeyword == NULL)
          break;
        if(strLine.find(pszKeyword) != string::npos)
        {
          strLine = strLine.substr(strLine.find(pszKeyword) + strlen(pszKeyword));
          break;
        }
      }
      closesocket(hSocket);
      if(strLine.find("<") != string::npos)
        strLine = strLine.substr(0, strLine.find("<"));
      strLine = strLine.substr(strspn(strLine.c_str(), " \t\n\r"));
      while(strLine.size() > 0 && isspace(strLine[strLine.size()-1]))
        strLine.resize(strLine.size()-1);
      CService addr(strLine,0,true);
      printf("GetMyExternalIP() received [%s] %s\n", strLine.c_str(), addr.ToString().c_str());
      if(!addr.IsValid() || !addr.IsRoutable())
        return false;
      ipRet.SetIP(addr);
      return true;
    }
  }