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之間的連接。 –