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);

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

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