2016-03-03 41 views
0

我在嘗試使用C++中的boost解析器解析端點時遇到了一個奇怪的問題。解決方法:沒有這樣的主機是已知的?

案例: 我試圖連接到一個網站http://localhostIpAddress/test/使用boost。 服務器的本地地址是「172.34.22.11」(比如說)。

我對着錯誤說「決心:沒有這樣的主機被稱爲

但是,當我連接到網站說如google.com它能夠解決和連接成功。 另外,即使我嘗試在瀏覽器中打開「http :: // localhostIpAddress/test /」,它也會成功打開。下面

是我的代碼:

int main() 
{ 
     std::cout << "\nWebClient is starting... \n"; 
     boost::asio::io_service IO_Servicehttp; 
     boost::asio::ip::tcp::resolver Resolverhttp(IO_Servicehttp); 
     std::string porthttp = "http"; 
     boost::asio::ip::tcp::resolver::query Queryhttp("172.34.22.11/test/", porthttp); 
     boost::asio::ip::tcp::resolver::iterator EndPointIteratorhttp = Resolverhttp.resolve(Queryhttp); 

     g_ClientHttp = new HTTPClient(IO_Servicehttp, EndPointIteratorhttp); 

    } 
    catch (std::exception& e) 
    { 
     std::cerr << e.what(); 
    } 
} 

在HTTPClient.cpp

HTTPClient::HTTPClient(boost::asio::io_service& IO_Servicehttp, boost::asio::ip::tcp::resolver::iterator EndPointIterhttp) 
: m_IOServicehttp(IO_Servicehttp), m_Sockethttp(IO_Servicehttp),m_EndPointhttp(*EndPointIterhttp) 
{ 
    std::cout << "\n Entered: HTTPClient ctor \n"; 
    boost::asio::ip::tcp::resolver::iterator endhttp; 
    boost::system::error_code error= boost::asio::error::host_not_found; 

    try 
    { 
     while (error && EndPointIterhttp != endhttp) //if error go to next endpoint 
     { 
      m_Sockethttp.async_connect(m_EndPointhttp,boost::bind(&HTTPClient::OnConnect_http, this, boost::asio::placeholders::error, ++EndPointIterhttp)); 
     } 
     if(error) 
      throw boost::system::system_error(error); 
    } 

    catch (std::exception& e) 
    { 
     std::cerr << e.what() << std::endl; 
    } 
    m_IOServicehttp.run(); 
} 

我已經經歷了很多網站由谷歌直接的走了,但還沒有找到與此相關的任何問題。 任何幫助或建議將不勝感激

回答

0

被解析的主機名是無效的。嘗試將解析器的查詢主機更改爲「172.34.22.11」。在URL中, 「http://172.34.22.11/test/」:

  • 「HTTP」 是協議
  • 「172.34.22.11」 是一個需要解決的主機
  • 「/測試/ 「是路徑

在高層次上,客戶端和服務器(主機)之間通過TCP進行網絡通信。客戶端將創建一個HTTP請求,將該路徑包含爲請求的一部分,並將完整請求寫入TCP套接字。服務器將從TCP套接字讀取HTTP請求,根據路徑處理請求,然後通過TCP向客戶端寫入HTTP響應。


主機名被串接用點和指定爲僅允許:

  • ASCII字母 'a' 到 'z'
  • 數字
  • 連字符

因此,「 172.34.22.11/test/「包含無效字符,並且可能無法解析。有關更多詳細信息,請參閱RFC952RFC1123

+0

感謝您的反饋意見。 我已經嘗試解析主機名 - 「172.34.22.11」,並且工作正常。 但我的要求是發送一些數據到/測試/,在這種情況下,我需要獲得完整的URL「http://172.34.22.11/test/」。 那我該怎麼做?如果你能指導我正確的方向,這將是非常有用的,因爲我是網絡領域的新手。 – harry

+0

此外,雖然通過stackoverflow帖子看,我發現每一個建議使用POCO或CURL庫進行HTTP/HTTPS連接/數據傳輸。那麼這是否意味着提升對HTTP不是一個好的選擇?由於我在我的應用程序中使用boost來提供其他purppose,因此我還認爲它也用於HTTP通信。 – harry

+0

@harry如果目的是通過編寫HTTP客戶端來了解協議,那麼[Asio HTTP客戶端示例](http://www.boost.org/doc/libs/1_60_0/doc/html/ boost_asio/examples/cpp03_examples.html#boost_asio.examples.cpp03_examples.http_client)可能是一個很好的開始,並且可以幫助理解HTTP請求是如何發送給主機而不是URL的。另一方面,如果只需要通過HTTP進行通信,那麼使用經過充分測試的,成熟的現有URL庫(如libcurl)將是一個好主意。 –

相關問題