views:

204

answers:

3
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;
}

The error is

"Unknown Error"

and here is the main function

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;
}

So it should catch any exceptions as far as I know. How can I fix this? (There shouldn't an exception at all since it's connected to google.com and winsock is initialized etc)

UPDATE: The error is actually being thrown after WSAConnect but there shouldn't be a problem connecting and none of my catch statements are being used for some reason.

UPDATE 2: Well now it catches the error but it says "Unknown Error" which is useless to me. Why won't it connect to google?

SOLVED: thanks!

+2  A: 

strerror() returns a char* on windows so you need a catch(char* error)

Gary
+1  A: 
robinjam
+1  A: 

strerror() is not appropriate here. It looks like you're trying to move Unix code to Windows; strerror() is the right thing on Unix. connect() on Unix stores error codes in the global errno value, and strerror() translates errno codes to error strings. Winsock handles error codes entirely differently, even down to the actual error values, so that they're not compatible with strerror().

See item 2.8 in the Winsock Programmer's FAQ for the correct way to turn Winsock error numbers into error message strings.

Warren Young