谢谢你们的帮助,伙计们!我已经编辑了我的源代码,现在它运行良好且没有违规,它确实连接到远程主机:
#include <iostream>
#include <memory>
#include <WinSock2.h>
#pragma comment(lib, "Ws2_32.lib")
typedef struct Header
{
SOCKET sock;
SOCKADDR_IN addr;
WORD WSAVersion;
WSAData data;
char *ip;
u_short port;
int result;
} Header;
class Connector
{
private:
std::unique_ptr<Header> obj;
public:
Connector(void)
{
obj.reset(new Header);
obj->ip = "193.201.231.44";
obj->port = 2775;
obj->WSAVersion = 0x202;
obj->addr.sin_family = AF_INET;
obj->addr.sin_addr.s_addr = inet_addr(obj->ip);
obj->addr.sin_port = htons(obj->port);
this->MakeConnection(&obj);
}
~Connector(void)
{
obj.release();
}
int MakeConnection(std::unique_ptr<Header> *pointer)
{
(*pointer)->result = WSAStartup((*pointer)->WSAVersion, &(*pointer)->data);
if((*pointer)->result != NO_ERROR)
{
std::cout << "WSA failed to start with the error: " << std::endl << (*pointer)->result << std::endl;
return 0;
}
else
{
std::cout << "WSA started successfully" << std::endl;
(*pointer)->sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if((*pointer)->sock == SOCKET_ERROR)
{
std::cout << "Failed to init new socket, with the error: " << WSAGetLastError() << std::endl;
return 0;
}
else
{
(*pointer)->result = connect(obj->sock, (sockaddr*)&(*pointer)->addr, sizeof((*pointer)->addr));
if((*pointer)->result == SOCKET_ERROR)
{
std::cout << "Failed to connect to the remote host " << (*pointer)->ip << ":" << (*pointer)->port
<< ", with the error: " << WSAGetLastError() << std::endl;
return 0;
}
else
{
std::cout << "Connected to the remote host " << (*pointer)->ip << ":" << (*pointer)->port << std::endl;
return 1;
}
}
}
}
};
void init(void)
{
std::unique_ptr<Connector> obj;
obj.reset(new Connector);
obj.release();
}
int main(void)
{
init();
return 0;
}