0

我有一些问题HttpWebRequest。我试图管理带有Web服务器的服务器和使用CF 2.0客户端的Windows CE 6.0之间的连接,我的实际目的是检索Windows CE计算机的外部IP。我试过使用HttpWebResponse,但在通话过程中卡住了。
现在我会更清楚,这是我在WinCE的机器上运行,以获得IP代码:HttpWebResponse没有回应

private string GetIPAddressRemote() 
    { 
     Uri validUri = new Uri("http://icanhazip.com"); 

     try 
     { 
      string externalIP = ""; 

      HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(validUri); 

      httpRequest.Credentials = CredentialCache.DefaultCredentials; 
      httpRequest.Timeout = 10000; // Just to haven't an endless wait 

      using (HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse()) 
      /* HERE WE ARE 
      * In this point my program stop working... 
      * well actually it doesn't throw any exception and doesn't crash at all 
      * For that reason I've setted the timeout property because in this part 
      * it starts to wait for a response that doesn't come 
      */ 
      { 
       using (Stream stream = httpResponse.GetResponseStream()) 
       { 
        // retrieve the return string and 
        // save it in the externalIP variable 
       } 
      } 

      return externalIP; 
     } 
     catch(Exception ex) 
     { 
      return ex.Message; 
     } 
    } 

那么,什么是我的问题吗?我不知道为什么它在拨打httpRequest.GetResponse()时遇到困难,有什么想法? 我必须说我是在一个代理下,所以我想出了这样一个想法,即代理可以阻止一些请求,可以吗?

回答

0

好吧,我想出了这样的事情:

private string GetIPAddressRemote() 
    { 
     Uri validUri = new Uri("http://icanhazip.com/"); 

     int tryNum = 0; 

     while (tryNum < 5) 
     { 
      tryNum++; 

      try 
      { 
       string externalIP = ""; 

       WebProxy proxyObj = new WebProxy("http://myProxyAddress:myProxyPort/", true); // Read this from settings 

       WebRequest request = WebRequest.Create(validUri); 

       request.Proxy = proxyObj; 
       request.Credentials = CredentialCache.DefaultCredentials; 
       request.Timeout = 10000; // Just to haven't an endless wait 

       using (WebResponse response = request.GetResponse()) 
       { 
        Stream dataStream = response.GetResponseStream(); 

        using (StreamReader reader = new StreamReader(dataStream)) 
        { 
         externalIP = reader.ReadToEnd(); 
        } 
       } 
       return externalIP; 
      } 
      catch (Exception ex) 
      { 
       if(tryNum > 4) 
        return ex.Message; 
      } 

      Thread.Sleep(1000); 
     } 
     return ""; 
    } 

但现在的问题是,没有任何信息检索。我的意思是,我从Stream解析字符串是html页面和检索是字符串:

<html> 
    <body> 
    <h1>It works!</h1> 
    <p>This is the default web page for this server.</p> 
    <p>The web server software is running but no content has been added, yet.</p> 
    </body> 
</html> 

现在我该怎么办?

+0

如果您的目标是获取服务器IP地址,您可以尝试使用DNS的主机名解析。否则,您可以更轻松地执行ping而不是WebRequest并从那里获取IP ... – salvolds

+0

不,我的目标是获取连接到服务器的计算机的IP。无论如何,现在我正在尝试另一条路线来获得机器和服务器之间以及服务器和另一台PC之间的连接。 –