2013-02-21 29 views
1

我在Windows上使用Boost :: ASIO版本1.52.0,在運行Win 8並使用VC++中的Visual Studio 2008代碼的測試計算機上使用SSL版本C.在asio中使用ip地址而不是url

我有一個成功連接到TCP服務器與給定的URL一些代碼:

// Create the resolver and query objects to resolve the host name in serverPath to an ip address. 
boost::asio::ip::tcp::resolver resolver(*IOService); 
boost::asio::ip::tcp::resolver::query query(serverPath, port); 
boost::asio::ip::tcp::resolver::iterator EndpointIterator = resolver.resolve(query); 
// Set up an SSL context. 
boost::asio::ssl::context ctx(*IOService, boost::asio::ssl::context::tlsv1_client); 
// Specify to not verify the server certificiate right now. 
ctx.set_verify_mode(boost::asio::ssl::context::verify_none); 
// Init the socket object used to initially communicate with the server. 
pSocket = new boost::asio::ssl::stream<boost::asio::ip::tcp::socket>(*IOService, ctx); 
// 
// The thread we are on now, is most likely the user interface thread. Create a thread to handle all incoming socket work messages. 
// This thread is created for each connection to a server. 
if (!RcvThreadCreated) 
{ 
    WorkerThreads.create_thread(boost::bind(&SSLSocket::RcvWorkerThread, this)); 
    RcvThreadCreated = true; 
    WorkerThreads.create_thread(boost::bind(&SSLSocket::SendWorkerThread, this)); 
} 
// Try to connect to the server. Note - add timeout logic at some point. 
boost::asio::async_connect(pSocket->lowest_layer(), EndpointIterator, 
    boost::bind(&SSLSocket::HandleConnect, this, boost::asio::placeholders::error)); 

基於一些研究,如果一個IP地址被替換不能使用能解決IP地址上面的代碼在serverPath中的URL。它看起來像正確的做法是創建一個這樣的端點:

const boost::asio::ip::address IP(boost::asio::ip::address::from_string(serverPath)); 
int iport = atoi(port.c_str()); 
boost::asio::ip::tcp::endpoint EP(IP, iport); 

這部分似乎編譯好。但是,稍後在async_connect方法中:

// Try to connect to the server. Note - add timeout logic at some point. 
boost::asio::async_connect(pSocket->lowest_layer(), EP, 
boost::bind(&SSLSocket::HandleConnect, this, boost::asio::placeholders::error)); 

它會生成一個錯誤。我猜測,async_connect方法想要查看第二個參數的迭代器。但是,我不確定如何創建一個。

根據以下link,答案表明可以使用套接字對象上的connect方法。但是,當我嘗試這樣做:

pSocket->connect(EP); 

編譯器提供了一個錯誤 - 錯誤C2039:

'connect' : is not a member of 'boost::asio::ssl::stream<Stream>' 

因此,有人可以顯示一些簡單的代碼,它提供了一種與連接到服務器一個IP地址,而不是一個URL?

如果這是不可能的,那麼有沒有辦法從IP地址進行反向查找來獲取URL?

+0

這不是很清楚,我在您的編譯失敗,你可以合併你的片段到一個單一的代碼塊的例子嗎? – 2013-02-22 16:55:17

回答

1

你async_connect( )代碼行不編譯因爲您傳遞的是成員函數指針而沒有將實例綁定到它。你已經在你的代碼的其他地方正確綁定了一個成員函數,所以我認爲這只是一個疏忽。正確的路線是這樣的:

pSocket->next_layer().async_connect(
    EP, 
    boost::bind(&SSLSocket::HandleConnect, this, boost::asio::placeholder::error)); 

至於你原來的問題,獲得了IP地址的終端,使用一個IP地址查詢IP :: TCP ::解析器工作正常,所以你不應該有有單獨的代碼路徑名稱和地址。使用ssl :: stream上的lowest_layer()來訪問底層的ip :: tcp :: socket是訪問connect()和async_connect()的正確方法。

除了創建SSL ::流與SSL ::上下文和使用async_handshake()建立連接後,你的SSL的代碼看起來應該幾乎相同的TCP代碼。你也可以在你的TCP代碼中使用lowest_layer()(它只是返回自己),這可以強調相似之處。

我不保證此代碼編譯,因爲我從工作中簡化它,但如果你做async_resolve(),你的決心處理方法看起來像(sp_是一個套接字/流指針):

void Pimpl::handleResolve(
    const boost::system::error_code& ec, 
    boost::asio::ip::tcp::resolver::iterator endpointIterator) { 
    if (ec) { 
    // error handling here 
    return;  
    } 
    sp_->lowest_layer().async_connect( 
    *endpointIterator, 
    boost::bind(&Pimpl::handleConnect, this, endpointIterator, boost::asio::placeholder::error)); 
} 

然後你的連接處理程序將看起來像(這嘗試的端點,直到它得到一個工程或沒有任何更多):

void Pimpl::handleConnect(
    boost::asio::ip::tcp::resolver::iterator endpointIterator, 
    const boost::system::error_code& ec) { 
    if (!ec) { 
    sp_->async_handshake(
     boost::asio::ssl::stream_base::client, 
     boost::bind(&Pimpl::handleHandshake, this, boost::asio::placeholder::error)); 
    } 
    else if (++endpointIterator != boost::asio::ip::tcp::resolver::iterator()) { 
    // Try connecting to the next endpoint. 
    sp_->lowest_layer().close(); 
    sp_->lowest_layer().async_connect(
     *endpointIterator, 
     boost::bind(&Pimpl::handleConnect, this, endpointIterator, boost::asio::placeholder::error)); 
    } 
    else { 
    // error handling here 
    } 
} 

,使這個特定的SSL ::流指針中唯一的一行而不是ip :: tcp :: socket指針async_handshake()調用。

+0

謝謝。當我有空時,我會試試看。 – 2013-03-01 00:44:20

0

我找到了解決問題的方法。我使用ssl :: stream類作爲套接字對象,並且出現錯誤的原因是因爲它沒有連接方法。然而,它有一個next_layer()方法,它返回一個可以調用connect或async_connect方法的對象。我在使用async_connect進行編譯時遇到了問題,但connect方法起作用。然後我打電話給我的HandleConnect方法事後,像這樣:

boost::system::error_code EC; 
pSocket->next_layer().connect(EP, EC); 
HandleConnect(EC); 

在回答的代碼@SamMiller請求時,它在下面給出。我仍然想知道如何爲boost :: asio :: async_connect調用爲端點創建一個迭代器,以及如何調用next_layer對象的async_connect方法。

void SSLSocket::Connect(SSLSocket* psSLS, const string& serverPath, string& port) 
{ 
    // Connects to the server. 
    // serverPath - specifies the path to the server. Can be either an ip address or url. 
    // port - port server is listening on. 
    // 
    try 
    { 
     Locking CodeLock(SocketLock); // Single thread the code. 
     // If the user has tried to connect before, then make sure everything is clean before trying to do so again. 
     if (pSocket) 
     { 
     delete pSocket; 
     pSocket = 0; 
     }                         
     // If serverPath is a URL, then resolve the address. 
     if ((serverPath[0] < '0') || (serverPath[0] > '9')) // Assumes that the first char of the server path is not a number when resolving to an ip addr. 
     { 
     // Create the resolver and query objects to resolve the host name in serverPath to an ip address. 
     boost::asio::ip::tcp::resolver resolver(*IOService); 
     boost::asio::ip::tcp::resolver::query query(serverPath, port); 
     boost::asio::ip::tcp::resolver::iterator EndpointIterator = resolver.resolve(query); 
     // Set up an SSL context. 
     boost::asio::ssl::context ctx(*IOService, boost::asio::ssl::context::tlsv1_client); 
     // Specify to not verify the server certificiate right now. 
     ctx.set_verify_mode(boost::asio::ssl::context::verify_none); 
     // Init the socket object used to initially communicate with the server. 
     pSocket = new boost::asio::ssl::stream<boost::asio::ip::tcp::socket>(*IOService, ctx); 
     // 
     // The thread we are on now, is most likely the user interface thread. Create a thread to handle all incoming socket work messages. 
     // This thread is created for each connection to a server. 
     if (!RcvThreadCreated) 
     { 
      WorkerThreads.create_thread(boost::bind(&SSLSocket::RcvWorkerThread, this)); 
      RcvThreadCreated = true; 
      WorkerThreads.create_thread(boost::bind(&SSLSocket::SendWorkerThread, this)); 
     } 
     // Try to connect to the server. Note - add timeout logic at some point. 
     boost::asio::async_connect(pSocket->lowest_layer(), EndpointIterator, 
      boost::bind(&SSLSocket::HandleConnect, this, boost::asio::placeholders::error)); 
     } 
     else 
     { 
     // serverPath is an ip address, so try to connect using that. 
     // 
     // Create an endpoint with the specified ip address. 
     const boost::asio::ip::address IP(boost::asio::ip::address::from_string(serverPath)); 
     int iport = atoi(port.c_str()); 
     const boost::asio::ip::tcp::endpoint EP(IP, iport); 
     // Set up an SSL context. 
     boost::asio::ssl::context ctx(*IOService, boost::asio::ssl::context::tlsv1_client); 
     // Specify to not verify the server certificiate right now. 
     ctx.set_verify_mode(boost::asio::ssl::context::verify_none); 
     // Init the socket object used to initially communicate with the server. 
     pSocket = new boost::asio::ssl::stream<boost::asio::ip::tcp::socket>(*IOService, ctx); 
     // 
     // The thread we are on now, is most likely the user interface thread. Create a thread to handle all incoming socket work messages. 
     // This thread is created for each connection to a server. 
     if (!RcvThreadCreated) 
     { 
      WorkerThreads.create_thread(boost::bind(&SSLSocket::RcvWorkerThread, this)); 
      RcvThreadCreated = true; 
      WorkerThreads.create_thread(boost::bind(&SSLSocket::SendWorkerThread, this)); 
     } 
     // Try to connect to the server. Note - add timeout logic at some point. 
     // pSocket->next_layer().async_connect(EP, &SSLSocket::HandleConnect); 
     boost::system::error_code EC; 
     pSocket->next_layer().connect(EP, EC); 
     if (EC) 
     { 
      // Log an error. This worker thread should exit gracefully after this. 
      stringstream ss; 
      ss << "SSLSocket::Connect: connect failed to " << sClientIp << " : " << uiClientPort << ". Error: " << EC.message() + ".\n"; 
      Log.LogString(ss.str(), LogError); 
     } 
     HandleConnect(EC); 
     } 
    } 
    catch (std::exception& e) 
    { 
     stringstream ss; 
     ss << "SSLSocket::Connect: threw an error - " << e.what() << ".\n"; 
     Log.LogString(ss.str(), LogError); 
     Stop(); 
    } 
} 

這是當下面的行所產生的錯誤:

pSocket->next_layer().async_connect(EP, &SSLSocket::HandleConnect); // Does not compile 

代替:

boost::system::error_code EC; 
pSocket->next_layer().connect(EP, EC); // Compiles and works properly. 

錯誤消息:

1>c:\boost_1_52_0\boost\asio\basic_socket.hpp(706) : error C2064: term does not evaluate to a function taking 1 arguments 
1>  c:\users\bob\documents\visual studio 2008\projects\attackpoker1\win32client\sslsockets\sslsocket.cpp(114) : see reference to function template instantiation 'void boost::asio::basic_socket<Protocol,SocketService>::async_connect<void(__thiscall SSLSocket::*)(const boost::system::error_code &)>(const boost::asio::ip::basic_endpoint<InternetProtocol> &,const ConnectHandler &)' being compiled 
1>  with 
1>  [ 
1>   Protocol=boost::asio::ip::tcp, 
1>   SocketService=boost::asio::stream_socket_service<boost::asio::ip::tcp>, 
1>   InternetProtocol=boost::asio::ip::tcp, 
1>   ConnectHandler=void (__thiscall SSLSocket::*)(const boost::system::error_code &) 
1>  ] 
相關問題