[英]Why doesn't this C++ code work?
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:现在,它捕获了错误,但显示“未知错误”,这对我没有用。 为什么不连接到Google?
解决:谢谢!
strerror()在Windows上返回char *,因此您需要catch(char *错误)
strerror()在这里不合适。 看来您正在尝试将Unix代码移至Windows; 在Unix上,strerror()是正确的选择。 Unix上的connect()将错误代码存储在全局errno
值中,而strerror()将errno
代码转换为错误字符串。 Winsock处理错误代码的方式完全不同,甚至低至实际错误值,因此它们与strerror()不兼容。
有关将Winsock错误编号转换为错误消息字符串的正确方法,请参见Winsock程序员常见问题解答中的2.8 。
抱歉,我打算将其发布为答案而不是评论。
您正在抛出一个char*
但是没有catch子句可以捕获它。 也许这就是您想要做的:
if(WSAConnect(this->_socket, (sockaddr *)&addr, sizeof(addr), NULL, NULL, NULL, NULL) != 0) throw std::runtime_error(strerror(WSAGetLastError()));
更新:
使用WSAConnect()而不是connect()有什么特殊的原因吗? 这应该工作:
_socket = socket(AF_INET, SOCK_STREAM, NULL); if ( connect( _socket, &addr, sizeof addr ) == SOCKET_ERROR ) { //Error }
您可能还会发现这很有用: http : //www.madwizard.org/programming/tutorials/netcpp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.