Socket Creation
This section covers the core functions for creating and managing sockets in the Windows Sockets API (Winsock). Sockets are endpoints for sending and receiving data across a network. The fundamental operation is creating a socket, which establishes a communication endpoint.
socket() Function
The socket() function creates a socket that is bound to a specific transport service provider. It returns a socket descriptor that can be used in subsequent socket functions.
SOCKET socket(int af, int type, int protocol);
Parameters
| Parameter | Description |
|---|---|
af |
The address family. For IPv4, use AF_INET. For IPv6, use AF_INET6. |
type |
The socket type. Common values include:
|
protocol |
The protocol to be used with the socket. For most common scenarios, this is set to 0 to automatically select the protocol corresponding to the socket type. For example, IPPROTO_TCP for stream sockets or IPPROTO_UDP for datagram sockets. |
Return Value
If the socket() function succeeds, it returns a value of type SOCKET representing the newly created socket. If the function fails, it returns INVALID_SOCKET. To get extended error information, call WSAGetLastError().
Remarks
When you call socket(), the Winsock DLL allocates a socket descriptor and associates it with the specified address family, socket type, and protocol. The socket is created in the closed state.
The protocol parameter is typically set to 0, allowing the system to choose the most appropriate protocol for the given af and type combination. However, you can specify a protocol number directly if needed, often obtained from protocol-specific header files.
WSAStartup() function. Similarly, before your application exits, you should call WSACleanup() to de-initialize the Winsock DLL.
Example
#include <winsock2.h>
#include <ws2tcpip.h>
// Link with Ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")
int main() {
WSADATA wsaData;
SOCKET clientSocket;
struct sockaddr_in serverAddr;
// Initialize Winsock
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed: %d\n", iResult);
return 1;
}
// Create a TCP/IP stream socket for client
clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (clientSocket == INVALID_SOCKET) {
printf("socket creation failed: %d\n", WSAGetLastError());
WSACleanup();
return 1;
}
printf("Socket created successfully!\n");
// ... further socket operations ...
// Clean up Winsock
WSACleanup();
return 0;
}