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

错误是

“未知错误”

这是主要功能

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:现在它捕获了错误,但它说“未知错误”,这对我来说没用。为什么连接不上谷歌?

已解决:谢谢!

4

3 回答 3

2

strerror() 在这里不合适。看起来您正试图将 Unix 代码移至 Windows;strerror() 在 Unix 上是正确的。Unix 上的 connect() 将错误代码存储在全局errno值中,而 strerror() 将errno代码转换为错误字符串。Winsock 以完全不同的方式处理错误代码,甚至处理实际的错误值,因此它们与 strerror() 不兼容。

有关将 Winsock 错误编号转换为错误消息字符串的正确方法,请参阅Winsock 程序员常见问题解答中的第2.8 项。

于 2010-06-21T15:38:53.820 回答
2

strerror() 在 Windows 上返回一个 char*,所以你需要一个 catch(char* error)

于 2010-06-20T02:55:29.423 回答
1

抱歉,我的意思是将此作为答案而不是评论发布。

你正在抛出一个char*但没有 catch 子句来捕捉它。也许这就是你想要做的:

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

更新:

您使用 WSAConnect() 而不是 connect() 有什么特别的原因吗?这应该有效:

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

您可能还会发现这很有用:http: //www.madwizard.org/programming/tutorials/netcpp

于 2010-06-20T02:57:12.513 回答