c/c++ windows api socket wrappers

#include <WinSock2.h>
#include <WS2tcpip.h>

#pragma comment(lib, "Ws2_32.lib")

class SocketWrapper {
public:
    SocketWrapper() : socket_(INVALID_SOCKET) {
        WSADATA wsaData;
        WSAStartup(MAKEWORD(2, 2), &wsaData);
    }

    ~SocketWrapper() {
        if (socket_ != INVALID_SOCKET) {
            closesocket(socket_);
        }
        WSACleanup();
    }

    bool CreateSocket() {
        socket_ = socket(AF_INET, SOCK_STREAM, 0);
        return socket_ != INVALID_SOCKET;
    }

    bool Connect(const char* ipAddress, int port) {
        sockaddr_in serverAddress{};
        serverAddress.sin_family = AF_INET;
        serverAddress.sin_port = htons(port);
        inet_pton(AF_INET, ipAddress, &serverAddress.sin_addr);

        return connect(socket_, reinterpret_cast<sockaddr*>(&serverAddress), sizeof(serverAddress)) != SOCKET_ERROR;
    }

    bool SendData(const char* data, int dataSize) {
        return send(socket_, data, dataSize, 0) != SOCKET_ERROR;
    }

    int ReceiveData(char* buffer, int bufferSize) {
        return recv(socket_, buffer, bufferSize, 0);
    }

private:
    SOCKET socket_;
};

Explanation:

  1. Include necessary headers for Windows Socket API (WinSock2.h and WS2tcpip.h).
  2. Link against the Winsock library (Ws2_32.lib).
  3. Create a class named SocketWrapper to encapsulate socket functionality.
  4. Define a constructor to initialize Winsock using WSAStartup.
  5. Define a destructor to clean up resources, including closing the socket and calling WSACleanup.
  6. Implement the CreateSocket method to create a socket using socket function.
  7. Implement the Connect method to connect to a server with the specified IP address and port using connect function.
  8. Implement the SendData method to send data over the socket using the send function.
  9. Implement the ReceiveData method to receive data from the socket using the recv function.
  10. Use the sockaddr_in structure to represent the server address and initialize it with the provided IP address and port.
  11. The inet_pton function converts the IP address from a string to a binary form.
  12. The htons function converts the port number to network byte order.
  13. The class member socket_ represents the socket created by the wrapper.

Note: This is a basic example, and error handling is minimal for brevity. In a production environment, you should add more robust error checking and handling.