C++ winsock accepter les connexions

Résolu/Fermé
Flayme - Modifié le 24 févr. 2023 à 13:36
mamiemando Messages postés 33160 Date d'inscription jeudi 12 mai 2005 Statut Modérateur Dernière intervention 24 juin 2024 - 24 févr. 2023 à 13:38

Bonjour,

Je suis débutant en c++, assez bon en python. Pour approfondir mes connaissances en c++, j'ai essayé de créer un server et un client TCP avec c++ et la librairie winsock.

Mais mon client ne se connecte pas au server (l'erreur connexionError que j'ai créée est levée), et je pense que c'est dû à mon pare feu (bizarre car j'arrive à faire des serveurs TCP en python).

Si c'est mon pare-feu, comment puis-je le désactiver sans les droits d'administrateur.

Voici le code du serveur:

#include <iostream>
#include <string>
#include <exception>

#include <winsock2.h>
#include <ws2tcpip.h>

// errors
class WSAError : public std::exception
{
    private:
    std::string message;

    public:
    WSAError(std::string msg)
    {
        message = msg;
    }
    std::string what () 
    {
        return message;
    }
};

class socketError : public std::exception
{
    private:
    std::string message;

    public:
    socketError(std::string msg)
    {
        message = msg;
    }
    std::string what () 
    {
        return message;
    }
};

class bindingError : public std::exception
{
    private:
    std::string message;

    public:
    bindingError(std::string msg)
    {
        message = msg;
    }
    std::string what () 
    {
        return message;
    }
};

class listeningError : public std::exception
{
    private:
    std::string message;

    public:
    listeningError(std::string msg)
    {
        message = msg;
    }
    std::string what () 
    {
        return message;
    }
};

class acceptError : public std::exception
{
    private:
    std::string message;

    public:
    acceptError(std::string msg)
    {
        message = msg;
    }
    std::string what () 
    {
        return message;
    }
};

int main()
{
    const int port = 5050;

    // init wsadata
    WSADATA wsaData;
    WORD wVersionRequested = MAKEWORD(2, 2);
    int wsaerr = WSAStartup(wVersionRequested, &wsaData);
    if (wsaerr != 0) throw(WSAError("WSAStartup failed, error code: " + std::to_string(wsaerr)));

    // create a socket
    SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (serverSocket == INVALID_SOCKET){
        WSACleanup();
        closesocket(serverSocket);
        throw(socketError("The creation of the socket failed, error: " + std::to_string(WSAGetLastError())));
    }

    // bind socket
    sockaddr_in service;
    service.sin_family = AF_INET;
    service.sin_addr.s_addr = inet_addr("127.0.0.1");
    service.sin_port = htons(port);
    memset( &( service.sin_zero ), '\0', 8 );
    if (bind(serverSocket, (sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
    {
        closesocket(serverSocket);
        WSACleanup();
        throw(bindingError("The binding of the socket failed, error: " + std::to_string(WSAGetLastError())));
    }

    // listen for socket
    if (listen(serverSocket, 1) == SOCKET_ERROR) // SOMAXCONN
    {
        closesocket(serverSocket);
        WSACleanup();
        throw(listeningError("Listening failed, error: " + std::to_string(WSAGetLastError())));
    }

    // accept
    SOCKET acceptSocket = accept(serverSocket, NULL, NULL); // ! ERROR PARE FEU
    if (acceptSocket == INVALID_SOCKET)
    {
        closesocket(serverSocket);
        WSACleanup();
        throw(acceptError("Accepting the socket failed, error: " + std::to_string(WSAGetLastError())));
    }

    // * CODE


    // cleanup
    closesocket(serverSocket);
    WSACleanup();
    std::cout << "OK!";
}

et celui du client:

#include <iostream>
#include <string>
#include <exception>

#include <winsock2.h>
#include <ws2tcpip.h>

class WSAError : public std::exception
{
    private:
    std::string message;

    public:
    WSAError(std::string msg)
    {
        message = msg;
    }
    std::string what () 
    {
        return message;
    }
};

class socketError : public std::exception
{
    private:
    std::string message;

    public:
    socketError(std::string msg)
    {
        message = msg;
    }
    std::string what () 
    {
        return message;
    }
};

class connexionError : public std::exception
{
    private:
    std::string message;

    public:
    connexionError(std::string msg)
    {
        message = msg;
    }
    std::string what () 
    {
        return message;
    }
};

int main()
{
    const int port = 5050;

    // init wsadata
    WSADATA wsaData;
    WORD wVersionRequested = MAKEWORD(2, 2);
    int wsaerr = WSAStartup(wVersionRequested, &wsaData);
    if (wsaerr != 0) throw(WSAError("WSAStartup failed, error code: " + std::to_string(wsaerr)));

    // create a socket
    SOCKET clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (clientSocket == INVALID_SOCKET){
        WSACleanup();
        closesocket(clientSocket);
        throw(socketError("The creation of the socket failed, error: " + std::to_string(WSAGetLastError())));
    }

    // connect the socket
    sockaddr_in service;
    service.sin_family = AF_INET;
    service.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
    service.sin_port = htons(port);
    memset( &( service.sin_zero ), '\0', 8 );
    if (connect(clientSocket, (sockaddr*)&clientSocket, sizeof(clientSocket)) == SOCKET_ERROR)
    {
        WSACleanup();
        closesocket(clientSocket);
        throw(connexionError("The connexion to the socket failed"));
    }

    // * CODE


    // cleanup
    WSACleanup();
    closesocket(clientSocket);
    std::cout << "OK!";
}

(pour compiler, j'utilise bien -lws2_32 à la fin)

Merci d'avance pour votre aide,
Flayme

A voir également:

1 réponse

J'ai résolu mon problème tout seul, il y avait des problèmes partout, je peux pas expliquer, mais c'est bien mon code et pas le pare feu.

serveur :

#include <iostream>
#include <string>
#include <exception>

#include <winsock2.h>
#include <ws2tcpip.h>

// errors
class WSAError : public std::exception
{
    private:
    std::string message;

    public:
    WSAError(std::string msg)
    {
        message = msg;
    }
    std::string what () 
    {
        return message;
    }
};

class socketError : public std::exception
{
    private:
    std::string message;

    public:
    socketError(std::string msg)
    {
        message = msg;
    }
    std::string what () 
    {
        return message;
    }
};

class bindingError : public std::exception
{
    private:
    std::string message;

    public:
    bindingError(std::string msg)
    {
        message = msg;
    }
    std::string what () 
    {
        return message;
    }
};

class listeningError : public std::exception
{
    private:
    std::string message;

    public:
    listeningError(std::string msg)
    {
        message = msg;
    }
    std::string what () 
    {
        return message;
    }
};

class acceptError : public std::exception
{
    private:
    std::string message;

    public:
    acceptError(std::string msg)
    {
        message = msg;
    }
    std::string what () 
    {
        return message;
    }
};

class sendError : public std::exception
{
    private:
    std::string message;

    public:
    sendError(std::string msg)
    {
        message = msg;
    }
    std::string what () 
    {
        return message;
    }
};

class recvError : public std::exception
{
    private:
    std::string message;

    public:
    recvError(std::string msg)
    {
        message = msg;
    }
    std::string what () 
    {
        return message;
    }
};

//copier coller InetPton
int inet_pton(int af, const char *src, void *dst);

int main()
{
    const int port = 5050;
    const int buffer_size = 1024;
    std::string error;

    // init wsadata
    WSADATA wsaData;
    WORD wVersionRequested = MAKEWORD(2, 2);
    int wsaerr = WSAStartup(wVersionRequested, &wsaData);
    if (wsaerr != 0) throw(WSAError("WSAStartup failed, error code: " + std::to_string(wsaerr)));

    // create a socket
    SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (serverSocket == INVALID_SOCKET){
        error = "The creation of the socket failed, error: " + std::to_string(WSAGetLastError());
        WSACleanup();
        closesocket(serverSocket);
        throw(socketError(error));
    }

    // bind socket
    sockaddr_in service;
    service.sin_family = AF_INET;
    inet_pton(AF_INET, "127.0.0.1", (SOCKADDR*)&service.sin_addr.s_addr);
    service.sin_port = htons(port);

    if (bind(serverSocket, (SOCKADDR*)&service, sizeof(service)) == SOCKET_ERROR)
    {
        error = "The binding of the socket failed, error: " + std::to_string(WSAGetLastError());
        closesocket(serverSocket);
        WSACleanup();
        throw(bindingError(error));
    }

    // listen for socket
    if (listen(serverSocket, SOMAXCONN) == SOCKET_ERROR)
    {
        error = "Listening failed, error: " + std::to_string(WSAGetLastError());
        closesocket(serverSocket);
        WSACleanup();
        throw(listeningError(error));
    }

    // accept
    std::cout << "Accepting ...\n";
    SOCKET acceptSocket = accept(serverSocket, NULL, NULL);
    if (acceptSocket == INVALID_SOCKET)
    {
        error = "Accepting the socket failed, error: " + std::to_string(WSAGetLastError());
        closesocket(serverSocket);
        WSACleanup();
        throw(acceptError(error));
    }

    // * CODE
    // recv
    char buffer[buffer_size];
    int byteCount = recv(acceptSocket, buffer, buffer_size, 0);
    try 
    {
        if (byteCount < 0)
        {
            error = "receving failed, error code: " + std::to_string(WSAGetLastError());
            WSACleanup();
            closesocket(acceptSocket);
            closesocket(serverSocket);
            throw(recvError(error));
        }
    }
    catch(recvError err)
    {
        std::cout << err.what() << '\n';
        throw(err);
    }
    std::cout << "Client send " << byteCount << " bytes\nThe message is \"" << buffer << "\"\n";

    // send
    char sendBuffer[buffer_size] = "Hello from the server";
    byteCount = send(acceptSocket, sendBuffer, buffer_size, 0);
    if (byteCount == SOCKET_ERROR)
    {
        error = "sending failed, error code: " + std::to_string(WSAGetLastError());
        WSACleanup();
        closesocket(acceptSocket);
        closesocket(serverSocket);
        throw(sendError(error));
    }
    std::cout << "I send " << byteCount << " bytes \n";

    // cleanup
    closesocket(acceptSocket);
    closesocket(serverSocket);
    WSACleanup();
}

int inet_pton(int af, const char *src, void *dst)
{
  struct sockaddr_storage ss;
  int size = sizeof(ss);
  char src_copy[INET6_ADDRSTRLEN+1];

  ZeroMemory(&ss, sizeof(ss));
  /* stupid non-const API */
  strncpy (src_copy, src, INET6_ADDRSTRLEN+1);
  src_copy[INET6_ADDRSTRLEN] = 0;

  if (WSAStringToAddress(src_copy, af, NULL, (struct sockaddr *)&ss, &size) == 0) {
    switch(af) {
      case AF_INET:
    *(struct in_addr *)dst = ((struct sockaddr_in *)&ss)->sin_addr;
    return 1;
      case AF_INET6:
    *(struct in6_addr *)dst = ((struct sockaddr_in6 *)&ss)->sin6_addr;
    return 1;
    }
  }
  return 0;
}

client :

#include <iostream>
#include <string>
#include <exception>

#include <winsock2.h>
#include <ws2tcpip.h>

class WSAError : public std::exception
{
    private:
    std::string message;

    public:
    WSAError(std::string msg)
    {
        message = msg;
    }
    std::string what () 
    {
        return message;
    }
};

class socketError : public std::exception
{
    private:
    std::string message;

    public:
    socketError(std::string msg)
    {
        message = msg;
    }
    std::string what () 
    {
        return message;
    }
};

class connexionError : public std::exception
{
    private:
    std::string message;

    public:
    connexionError(std::string msg)
    {
        message = msg;
    }
    std::string what () 
    {
        return message;
    }
};

class sendError : public std::exception
{
    private:
    std::string message;

    public:
    sendError(std::string msg)
    {
        message = msg;
    }
    std::string what () 
    {
        return message;
    }
};

class recvError : public std::exception
{
    private:
    std::string message;

    public:
    recvError(std::string msg)
    {
        message = msg;
    }
    std::string what () 
    {
        return message;
    }
};

//copier coller InetPton
int inet_pton(int af, const char *src, void *dst);


int main()
{
    const int port = 5050;
    const int buffer_size = 1024;
    std::string error;

    // init wsadata
    WSADATA wsaData;
    WORD wVersionRequested = MAKEWORD(2, 2);
    int wsaerr = WSAStartup(wVersionRequested, &wsaData);
    if (wsaerr != 0) throw(WSAError("WSAStartup failed, error code: " + std::to_string(wsaerr)));

    // create a socket
    SOCKET clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (clientSocket == INVALID_SOCKET){
        error = "The creation of the socket failed, error code: " + std::to_string(WSAGetLastError());
        WSACleanup();
        closesocket(clientSocket);
        throw(socketError(error));
    }

    // connect the socket
    sockaddr_in service;
    service.sin_family = AF_INET;
    inet_pton(AF_INET, "127.0.0.1", (SOCKADDR*)&service.sin_addr.s_addr);
    service.sin_port = htons(port);

    if (connect(clientSocket, (SOCKADDR*)&service, sizeof(service)) == SOCKET_ERROR)
    {
        error = "The connexion to the socket failed, error code: " + std::to_string(WSAGetLastError());
        WSACleanup();
        closesocket(clientSocket);
        throw(connexionError(error));
    }

    // * CODE
    // send
    char buffer[buffer_size] = "Hello from the client";
    int byteCount = send(clientSocket, buffer, buffer_size, 0);
    if (byteCount == SOCKET_ERROR)
    {
        error = "sending failed, error code: " + std::to_string(WSAGetLastError());
        WSACleanup();
        closesocket(clientSocket);
        throw(sendError(error));
    }
    std::cout << "I send " << byteCount << " bytes \n";

    // recv
    try
    {
        byteCount = recv(clientSocket, buffer, buffer_size, 0);
        if (byteCount < 0)
        {
            error = "receving failed, error code: " + std::to_string(WSAGetLastError());
            WSACleanup();
            closesocket(clientSocket);
            throw(recvError(error));
        }
    }
    catch (recvError err)
    {
        std::cout << err.what() << '\n';
        throw(err);
    }
    std::cout << "Server send " << byteCount << " bytes\nThe message is \"" << buffer << "\"\n";

    // cleanup
    WSACleanup();
    closesocket(clientSocket);
}

int inet_pton(int af, const char *src, void *dst)
{
  struct sockaddr_storage ss;
  int size = sizeof(ss);
  char src_copy[INET6_ADDRSTRLEN+1];

  ZeroMemory(&ss, sizeof(ss));
  /* stupid non-const API */
  strncpy (src_copy, src, INET6_ADDRSTRLEN+1);
  src_copy[INET6_ADDRSTRLEN] = 0;

  if (WSAStringToAddress(src_copy, af, NULL, (struct sockaddr *)&ss, &size) == 0) {
    switch(af) {
      case AF_INET:
    *(struct in_addr *)dst = ((struct sockaddr_in *)&ss)->sin_addr;
    return 1;
      case AF_INET6:
    *(struct in6_addr *)dst = ((struct sockaddr_in6 *)&ss)->sin6_addr;
    return 1;
    }
  }
  return 0;
}
0
mamiemando Messages postés 33160 Date d'inscription jeudi 12 mai 2005 Statut Modérateur Dernière intervention 24 juin 2024 7 760
24 févr. 2023 à 13:38

Merci pour ces précisions. Pense quand tu partages un extrait de code à spécifier le langage mis en jeu avec le menu déroulant en haut à gauche. Pour plus de précisions, voir ce lien.

Bonne continuation

0