Creating a Socket (Winsock)

MSDN Documentation > Windows > API Reference > Networking > Winsock > Creating a Socket

This section describes how to create a socket using the Winsock API. A socket is an endpoint for communication.

Introduction to Socket Creation

The primary function for creating a socket is socket(). This function allows you to specify the address family, socket type, and protocol for the socket.

The socket() Function

The socket() function is declared as follows:

SOCKET socket(
  int af,
  int type,
  int protocol
);

Parameters

Return Value

If the socket is created successfully, socket() returns a descriptor for the new socket. Otherwise, it returns INVALID_SOCKET, and a specific error code can be retrieved by calling WSAGetLastError().

Example: Creating a TCP/IP Socket

The following code snippet demonstrates how to create a TCP/IP socket for IPv4 communication:

#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib") // Link with ws2_32.lib

SOCKET clientSocket = INVALID_SOCKET;
int iResult;

// Initialize Winsock
WSADATA wsaData;
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0) {
    printf("WSAStartup failed: %d\n", iResult);
    return 1;
}

// Create a SOCKET for connecting to server
clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (clientSocket == INVALID_SOCKET) {
    printf("Error at socket(): %ld\n", WSAGetLastError());
    WSACleanup();
    return 1;
}

// Socket created successfully
printf("Socket created.\n");

// ... proceed with connect(), send(), recv(), etc.

// Cleanup
closesocket(clientSocket);
WSACleanup();
Important: Before using any Winsock functions, you must call WSAStartup() to initialize the Winsock DLL. Similarly, before your application exits, you should call WSACleanup() to free any resources allocated by Winsock.

Related Topics