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:
- Include necessary headers for Windows Socket API (
WinSock2.h
andWS2tcpip.h
). - Link against the Winsock library (
Ws2_32.lib
). - Create a class named
SocketWrapper
to encapsulate socket functionality. - Define a constructor to initialize Winsock using
WSAStartup
. - Define a destructor to clean up resources, including closing the socket and calling
WSACleanup
. - Implement the
CreateSocket
method to create a socket usingsocket
function. - Implement the
Connect
method to connect to a server with the specified IP address and port usingconnect
function. - Implement the
SendData
method to send data over the socket using thesend
function. - Implement the
ReceiveData
method to receive data from the socket using therecv
function. - Use the
sockaddr_in
structure to represent the server address and initialize it with the provided IP address and port. - The
inet_pton
function converts the IP address from a string to a binary form. - The
htons
function converts the port number to network byte order. - 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.