Skip to main content

Win32 Minimum Client Socket Transaction

This is the minimal WinAPI using winsock2.h

References: 

Requires linking against ws2_32

#include <winsock2.h>
#include <mstcpip.h>

int WINAPI WinMain(HINSTANCE  hInstance, HINSTANCE hPrevInstance, PSTR lpCmdLine, int nCmdShow){
    WORD wVersionRequired = MAKEWORD(2, 2);
    WSADATA wsaData;
    WSAStartup(wVersionRequired, &wsaData);

    // Create a socket
    SOCKET socket = WSASocketA(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, 0);
    if(socket == INVALID_SOCKET){
        cprintf("Socket was invalid with error %ld\n", WSAGetLastError());
    }

    // Establish the peer
    struct sockaddr_in peer;
    peer.sin_family = AF_INET;
    peer.sin_addr.s_addr = inet_addr("127.0.0.1");
    peer.sin_port = htons(50007);

    // Connect to a peer.
    int result = WSAConnect(socket, (SOCKADDR*) &peer, sizeof(peer), NULL, NULL, NULL, NULL);
    cprintf("Result: %ld\n", result);


    // Send some data
    // We use the WSABUF here.
    WSABUF buffer = {0};
    char* text = "This is some data. Hello.";
    buffer.buf = text;
    buffer.len = bstrlen(text) + 1;

    // Send
    DWORD dwBytesSent = 0;
    result = WSASend(socket, &buffer, 1, &dwBytesSent, 0, NULL, NULL);
    if (result == SOCKET_ERROR) {
        result = WSAGetLastError();
        cprintf("WSASend returned error %ld\n", result);
    } else {
        cprintf("Sent %u bytes across the channel.\n", dwBytesSent);
    }

    // Receive some data
    // Set the recipient buffer.
    #define maximumRecvSize 4000
    char* recvBuffer = (char*) valloc(maximumRecvSize);
    buffer.len = maximumRecvSize;
    buffer.buf = recvBuffer;
    
    DWORD dataFlags = 0;
    //Request the data.
    result = WSARecv(socket, &buffer, 1, &dwBytesSent, &dataFlags, NULL, NULL);
    if (result == SOCKET_ERROR) {
        result = WSAGetLastError();
        cprintf("WSARecv returned error %ld\n", result);
    } else {
        cprintf("Received %u bytes across the channel.\n", dwBytesSent);
        cprintf("Data: %s\n", buffer.buf);
    }


    // Close the socket
    result = closesocket(socket);
    cprintf("Result: %ld\n", result);
    
    WSACleanup();

    cprintf("Socket: %u\n", socket);
    return 0;
}