socket

socket creates a socket and returns an integer descriptor. The operation of socket is controlled by socket-level options that are defined. setsockopt and getsockopt functions are used to set and get options. By default, a socket is created in blocking mode. A socket must be closed with the closesocket.

Syntax

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

Parameters

af

Address family in which address specifies in subsequent socket operations will be interpreted.

type

Specifies the semantics of communications. Possible valies depend on the address family (af) and protocol. If type is 0, the first type that matched the address family(af) and protocol will be used.

protocol

Protocol to be used. Possible values depend on the address family (af). If the protocol is 0, the first protocol that matches the address family (af) will be used.

Address Family (af) Protocol (protocol) Socket Type (type)

AF_INET or
AF_INET6

IPPROTO_TCP

SOCK_STREAM

AF_INET or
AF_INET6

IPPROTO_UDP

SOCK_DGRAM

A SOCK_STREAM socket must be in a connected state before any data can be sent or received on it. Once connected, data can be transferred using some variant of the send and receive calls. TCP is used on SOCK_STREAM types to ensure that data is not lost or duplicated. If a piece of data for which the peer protocol has buffer space cannot be successfully transmitted in a reasonable length of time, the connection is considered broken and calls will return an error value of SOCKET_ERROR and set last error to WSAETIMEDOUT. If the SO_KEEPALIVE option is on, sockets are kept "warm" by forcing transmissions on a protocol-dependent frequency in the absence of other activity. An error is indicated if no response can be elicited on an otherwise idle connection for an extended period (also protocol-dependent). SOCK_DGRAM sockets allow sending and receiving of UDP datagrams or messages to correspondents named in sendto and recvfrom calls.

Return Value

The non-negative socket descriptor if the function succeeds, INVALID_SOCKET if the function fails

Use WSAGetLastError to retrieve a specific error code.

Remarks

You can use this code snippet to correctly make the socket call and check for an error:

#include <winsock2.h>
#include <ws2tcpip.h>
#include <rtapi.h>
	SOCKET sd = socket(AF_INET, SO_STREAM, IPPROTO_TCP);
	if ( sd == INVALID_SOCKET )
	{
		RtPrintf("Error: Unable to create socket(%d)\n",WSAGetLastError());
	}

Requirements

Minimum Supported Version RTX64 2013
Header Winsock2.h
Library RtTcpip.lib