2010-06-20 105 views
2
int Socket::Connect(const std::string& host, int port) 
{ 

    if(this->_connected) 
     throw "Socket is already connected"; 
    // Get the IP from the string 


    hostent* ip = gethostbyname(host.c_str()); 

    /*if(server == NULL) 
     throw strerror(WSAGetLastError());*/ 

    // Information for WinSock. 
    sockaddr_in addr; 
    // Clear up the memory 
    memset(&addr, 0, sizeof(addr)); 
    addr.sin_family = AF_INET; 
    addr.sin_port = htons(port); 
    addr.sin_addr = *((in_addr *)ip->h_addr); 

    // Try and connect 
    if(WSAConnect(this->_socket, (sockaddr *)&addr, sizeof(addr), NULL, NULL, NULL, NULL) != 0) 
     throw strerror(WSAGetLastError()); // this is being thrown but not caught? 
    this->_connected = true; 
    return 0; 
} 

的錯誤是這個C++代碼爲什麼不起作用?

「未知錯誤」

,這裏是主要的功能

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    try{ 


    Socket* socket = new Socket(); 
    if(socket->Connect("google.com", 80) == 0) 
     std::cout << "[-] connected..." << endl; 

    std::string line = socket->RecvLine(); 
    std::cout << line << endl; 
    } 
    catch(char* errcstr) 
    { 
     std::cout << errcstr << endl; 
    } 
    catch(int err) 
    { 
     std::cout << err << endl; 
    } 
    catch(std::string errstr) 
    { 
     std::cout << errstr << endl; 
    } 
    catch(exception ex) 
    { 
     std::cout << ex.what() << endl; 
    } 
    system("pause"); 
    return 0; 
} 

所以應該捕獲任何異常,據我所知。我怎樣才能解決這個問題? (因爲它連接到google.com和winsock被初始化等,所以不應該有任何例外)

更新:錯誤實際上是在WSAConnect之後引發的,但應該沒有連接問題,也沒有我的catch聲明由於某種原因正在使用。

更新2:現在它捕捉錯誤,但它說「未知的錯誤」,這對我沒用。爲什麼不能連接到谷歌?

求助:謝謝!所以你需要一個catch(字符*錯誤)

+0

'gethostbyname'是一個C API,不會拋出C++異常。你確定這是錯誤發生的地方嗎? – 2010-06-20 02:36:58

+3

啓用一次機會異常處理(在Visual Studio中,Ctrl + Alt + E並選中所有複選框)並運行附加到調試器。這將允許您在拋出異常時中斷。 – 2010-06-20 02:40:05

+0

謝謝詹姆斯。在WSAConnect之後就是一個例外(所以它沒有連接,並且我的catch語句沒有出於某種原因正在工作) – 2010-06-20 02:52:44

回答

2

字符串錯誤()返回在Windows上一個char *,我的意思是張貼此作爲一個答案不評論。

你扔char*,但沒有趕上它的條款。也許這是你想要做什麼:

 
if(WSAConnect(this->_socket, (sockaddr *)&addr, sizeof(addr), NULL, NULL, NULL, NULL) != 0) 
     throw std::runtime_error(strerror(WSAGetLastError())); 

UPDATE:

有你爲什麼使用WSAConnect(什麼特別的原因),而不是連接()?這應該工作:

 
_socket = socket(AF_INET, SOCK_STREAM, NULL); 
if (connect(_socket, &addr, sizeof addr) == SOCKET_ERROR) { 
    //Error 
} 

您也可能會發現這個有用:http://www.madwizard.org/programming/tutorials/netcpp

2

strerror()這樣是不恰當的位置。它看起來像你試圖將Unix代碼移到Windows上; strerror()在Unix上是正確的。 Unix上的connect()存儲全局errno值中的錯誤代碼,而strerror()將errno代碼轉換爲錯誤字符串。 Winsock完全不同的處理錯誤代碼,甚至到實際的錯誤值,以便它們與strerror()不兼容。

請參閱Winsock程序員常見問題中的item 2.8以將Winsock錯誤號碼轉換爲錯誤消息字符串的正確方法。

相關問題