Winsock Connection C ++无法连接到IPv4或外部IP地址

时间:2018-03-02 04:46:57

标签: c++ sockets winsock

所以我一直在开发用于多台计算机的东西(我在僵尸网络上工作以证明一个学校项目计算机很容易被黑客攻击作为GITA项目)而且我可以'似乎与服务器和客户端建立了连接。客户端可以通过127.0.0.1进行连接,但是,当尝试通过IPv4或外部ip连接时(可以在www.whatsmyip.org上找到),它似乎无法正常工作。所以我已经尝试了一切,甚至禁用我的防火墙,但没有。

我想知道我的代码是否碰巧弄错了?

客户端:

#include "client.h"

Client* Client::clientptr;

int Client::Initalize(const char* add)
{
    char ownPth[MAX_PATH];

    // When NULL is passed to GetModuleHandle, the handle of the exe itself is returned
    HMODULE hModule = GetModuleHandle(NULL);
    if (hModule != NULL)
    {
        // Use GetModuleFileName() with module handle to get the path
        GetModuleFileName(hModule, ownPth, (sizeof(ownPth)));
        std::cout << ownPth << std::endl;
    }
    else
    {
        std::cout << "Module handle is NULL" << std::endl;
    }

    WSAData wsaData;
    WORD DllVersion = MAKEWORD(2, 1);

    if (WSAStartup(DllVersion, &wsaData) != 0)
    {
        std::cout << "ERROR: WINSOCK INVALID!" << std::endl;
        exit(0);
    }

    std::cout << "Setting SOCKADDR_IN addr..." << std::endl;
    addrlen = sizeof(addr);
    addr.sin_addr.s_addr = inet_addr(add);
    addr.sin_port = htons(4403);
    addr.sin_family = AF_INET;

    connection = socket(AF_INET, SOCK_STREAM, NULL);

    while (true)
    {
        std::cout << "Attempting connection..." << std::endl;
        if (connect(connection, (SOCKADDR*)&addr, addrlen) > 0 || connect == 0)
        {
            std::cout << "Connection established!" << std::endl;
            break;
        }

        std::cout << "Error: Failed to connect! Retrying... " << std::endl;

        Sleep(1000);

    }

    clientptr = this;

    return 0;
}

int Client::Run()
{
    std::cout << std::endl << "Running..." << std::endl;

    while (true)
    {

        Sleep(10);
    }

    return 0;
}

服务器:

#include "server.h"

Server* Server::serverptr; //Serverptr is necessary so the static ClientHandler method can access the server instance/functions.

int Server::Initalize()
{
    std::cout << "Setting crash handler..." << std::endl;

    std::cout << "Looking at winsock dll version..." << std::endl;
    WSADATA wsaData;
    WORD DllVersion = MAKEWORD(2, 1);
    if (WSAStartup(DllVersion, &wsaData) != 0)
    {
        MessageBoxA(NULL, "Winsock startup failed", "Error", MB_OK | MB_ICONERROR);
        exit(1);
    }

    std::cout << "Creating listening socket..." << std::endl;

    addrlen = sizeof(addr);
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    addr.sin_port = htons(4403);
    addr.sin_family = AF_INET;

    std::cout << "The socket data addr "
        << "{"
        << "addr.sin_addr.s_addr = " << addr.sin_addr.s_addr
        << ", addr.sin_port = " << addr.sin_port
        << ", addr.sin_family = " << addr.sin_family
        << "}" << std::endl;

    sListen = socket(AF_INET, SOCK_STREAM, NULL); //Create socket to listen for new connections
    if (bind(sListen, (SOCKADDR*)&addr, sizeof(addr)) == SOCKET_ERROR) //Bind the address to the socket, if we fail to bind the address..
    {
        std::string ErrorMsg = "Failed to bind the address to our listening socket. Winsock Error:" + std::to_string(WSAGetLastError());
        MessageBoxA(NULL, ErrorMsg.c_str(), "Error", MB_OK | MB_ICONERROR);
        exit(1);
    }
    if (listen(sListen, SOMAXCONN) == SOCKET_ERROR) //Places sListen socket in a state in which it is listening for an incoming connection. Note:SOMAXCONN = Socket Oustanding Max connections, if we fail to listen on listening socket...
    {
        std::string ErrorMsg = "Failed to listen on listening socket. Winsock Error:" + std::to_string(WSAGetLastError());
        MessageBoxA(NULL, ErrorMsg.c_str(), "Error", MB_OK | MB_ICONERROR);
        exit(1);
    }

    std::cout << "Finalizing..." << std::endl;
    output = false;
    currClient = 0;

    std::cout << "Setting serverptr..." << std::endl;

    serverptr = this;

    std::cout << "Creating Threads..." << std::endl;

    serverptr->Listening = false;

    CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)Listen, NULL, NULL, NULL); //Create thread that will manage all outgoing packets

    while (serverptr->Listening == false);

    std::cout << "Done Initalizing!" << std::endl << std::endl;

    return 0;
}

int Server::Run()
{
    std::cout << "Running server...";

    serverptr->Listening = true;

    while (true)
    {
        std::string userinput;
        int inputInt;
        HANDLE hConsoe = GetStdHandle(STD_OUTPUT_HANDLE);

        while (true)
        {
            std::cout << std::endl << "] ";
            std::getline(std::cin, userinput);
            serverptr->HandleInput(userinput);
        }
    }

    return 0;
}

void Server::Listen()
{
    if (serverptr->output)
        std::cout << "Listener socket running..." << std::endl;

    serverptr->Listening = true;

    while (true)
    {
        if (serverptr->Listening == true)
        {

            SOCKET newConnection    //the connection for the socket
                = accept(serverptr->sListen, (SOCKADDR*)&serverptr->addr, &serverptr->addrlen); //Accept a new connection

            if (newConnection == 0)
            {
                if (serverptr->output)
                    std::cout << "FAILED TO ACCEPT THE CLIENTS CONNECTION!" << std::endl;
            }
            else
            {

                if (serverptr->output)
                {
                    std::cout << "A connection has been made [" << inet_ntoa(serverptr->addr.sin_addr) << "]!" << std::endl;
                    std::cout << "Creating Client(" << newConnection << ")..." << std::endl;
                }

                Client newClient(newConnection, serverptr->addr);
                int connectionId = serverptr->clients.size();

                serverptr->clients.push_back(newClient);

                CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)RecvClient, NULL, NULL, NULL); //Create thread that will manage all incomming packets

                int index = serverptr->clients.size() - 1;

                while (!serverptr->clients[index].Listening);

                if (serverptr->output)
                    std::cout << "Client success [" << (index + 1) << "]!" << std::endl;
            }
        }
    }

    return;
}


void Server::RecvClient()
{
    int index = serverptr->clients.size() - 1;
    char data[1600];

    if (serverptr->output)
        std::cout << "Listening for client[" << (index + 1) << "]..." << std::endl;

    serverptr->clients[index].Listening = true;

    while (true)
    {
        recv(serverptr->clients[index]._socket, data, sizeof(data), 0);
        if (serverptr->output)
            std::cout << "Data Recieved from client[" << (index + 1) << "]!" << std::endl;

        if ((int)data[0] < 0)
        {
            if (serverptr->output)
                std::cout << "Client [" << (index + 1) << "] is disconnecting with the current code {" << (int)data[0] << "}..." << std::endl;
            serverptr->DisconnectClient(index);
            break;
        }
    }

    if (serverptr->output)
        std::cout << "No longer listening for client[" << (index + 1) << "]!" << std::endl;

}

void Server::HandleInput(std::string string)
{
    std::string sHandle = string;
    std::istringstream iss(string);
    std::vector<std::string> sTokens((std::istream_iterator<std::string>(iss)),
        std::istream_iterator<std::string>());

    if (sHandle == "cls")
    {
        system("cls");
        return;
    }

    if (sHandle == "list")
    {
        int index = serverptr->clients.size() - 1;

        std::cout << "Total Clients: " << serverptr->clients.size() << std::endl;
        for (int i = 0; i < serverptr->clients.size(); i++)
        {
            std::cout << (char)195 << (char)196 << " Client [" << i + 1 << "] {" << serverptr->clients[i]._socket << ", " << inet_ntoa(serverptr->clients[i]._address.sin_addr) << "}" << std::endl;
        }

        return;
    }

    if (sHandle == "data")
    {
        std::cout << "Toggling data output..." << std::endl;
        serverptr->output = true;

        return;
    }

    if (sTokens[0] == "broadcast")
    {
        int change = 0;
        std::cout << "Toggling client: ";

        if (sTokens.size() > 1)
        {
            std::stringstream strings(sTokens[1]);
            strings >> change;

            if (change > serverptr->clients.size())
            {
                change = serverptr->clients.size();
            }
        }

        if (change > 0) std::cout << change << std::endl;
        else std::cout << "All" << std::endl;

        serverptr->currClient = change;

        return;
    }

    std::cout << "Error: Unknown command!" << std::endl;

    return;
}

void Server::DisconnectClient(int id)
{
    if (serverptr->output)
        std::cout << "void Server::DisconnectClient(" << id << ")..." << std::endl;
    closesocket(serverptr->clients[id]._socket);
    serverptr->clients.erase(serverptr->clients.begin() + (id));

    return;
}

Client::Client(SOCKET socket, SOCKADDR_IN address)
{
    this->_address = address;
    this->_socket = socket;
    this->Listening = false;
}

0 个答案:

没有答案