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.
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.
socket() FunctionThe socket() function is declared as follows:
SOCKET socket(
int af,
int type,
int protocol
);
af: The address family. Common values include:
AF_INET: IPv4 Internet protocols.AF_INET6: IPv6 Internet protocols.AF_UNSPEC: Unspecified address family. The system will attempt to determine the most appropriate.type: The socket type. Common values include:
SOCK_STREAM: A stream socket, typically used for connection-oriented protocols like TCP.SOCK_DGRAM: A datagram socket, typically used for connectionless protocols like UDP.protocol: The specific protocol to be used with the socket. For example, IPPROTO_TCP or IPPROTO_UDP. If set to 0, the system will choose the default protocol for the specified address family and socket type.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().
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();
WSAStartup() to initialize the Winsock DLL. Similarly, before your application exits, you should call WSACleanup() to free any resources allocated by Winsock.