Win32 Minimum Client Socket Transaction
This is the minimal WinAPI using winsock2.h
References:
- https://learn.microsoft.com/en-us/windows/win32/winsock/using-secure-socket-extensions
- https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
- https://learn.microsoft.com/en-us/windows/win32/api/winsock2/ns-winsock2-wsaprotocol_infoa
- https://learn.microsoft.com/en-us/windows/win32/api/ws2tcpip/nf-ws2tcpip-wsasetsocketsecurity
- https://learn.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-wsastartup
- https://learn.microsoft.com/en-us/windows/win32/api/mstcpip/ne-mstcpip-socket_security_protocol
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 = connect(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;
}