socket
SOCKET socket(
int af,
int type,
int protocol
);
Parameters
| Parameter | Description |
|---|---|
af |
The address family. This parameter can be one of the following:
|
type |
The socket type, which determines the semantics of communication by this socket. This parameter can be one of the following values defined in the Winsock header file:
|
protocol |
The protocol to be used with the socket. The valid values for the protocol parameter depend on the address family specified in the af parameter.
|
Return Value
If no error occurs, socket returns a descriptor for the newly created socket. This descriptor is a SOCKET value, which is an integer type. This value can be used in subsequent Winsock function calls to identify this socket instance.
If an error occurs, socket returns INVALID_SOCKET. To get extended error information, call WSAGetLastError.
Note
Winsock supports the following address families:
AF_INET(IPv4)AF_INET6(IPv6)AF_UNSPEC(Unspecified)
Winsock supports the following socket types:
SOCK_STREAM(for reliable, connection-oriented protocols like TCP)SOCK_DGRAM(for unreliable, connectionless protocols like UDP)SOCK_RAW(for raw socket access)
Important
You must call WSAStartup before calling any Winsock functions, including socket. You must call WSACleanup when you are finished using Winsock.
Remarks
The socket function creates a socket that is bound to a specific transport service provider. The transport service provider is specified by the af, type, and protocol parameters.
If the protocol parameter is set to 0, the Winsock service provider will use the default protocol associated with the requested socket type. For example, if af is AF_INET and type is SOCK_STREAM, setting protocol to 0 will select TCP.
The socket function is used to create endpoints for communication. The returned socket descriptor can then be used to establish connections, send or receive data, and manage network communication.
Example
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
// Link with Ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")
int main() {
WSADATA wsaData;
SOCKET sockfd = INVALID_SOCKET;
int iResult;
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed: %d\n", iResult);
return 1;
}
// Create a TCP/IP socket
sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sockfd == INVALID_SOCKET) {
printf("socket failed: %d\n", WSAGetLastError());
WSACleanup();
return 1;
}
printf("Socket created successfully.\n");
// You would typically bind, listen, accept, or connect here.
// For this example, we'll just close the socket.
iResult = closesocket(sockfd);
if (iResult == SOCKET_ERROR) {
printf("closesocket failed: %d\n", WSAGetLastError());
WSACleanup();
return 1;
}
printf("Socket closed successfully.\n");
// Clean up Winsock
WSACleanup();
return 0;
}