Windows apps
Collapse the table of content
Expand the table of content
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

setsockopt function

The setsockopt function sets a socket option.


int setsockopt(
  _In_       SOCKET s,
  _In_       int    level,
  _In_       int    optname,
  _In_ const char   *optval,
  _In_       int    optlen


s [in]

A descriptor that identifies a socket.

level [in]

The level at which the option is defined (for example, SOL_SOCKET).

optname [in]

The socket option for which the value is to be set (for example, SO_BROADCAST). The optname parameter must be a socket option defined within the specified level, or behavior is undefined.

optval [in]

A pointer to the buffer in which the value for the requested option is specified.

optlen [in]

The size, in bytes, of the buffer pointed to by the optval parameter.

Return value

If no error occurs, setsockopt returns zero. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code can be retrieved by calling WSAGetLastError.

Error codeMeaning

A successful WSAStartup call must occur before using this function.


The network subsystem has failed.


The buffer pointed to by the optval parameter is not in a valid part of the process address space or the optlen parameter is too small.


A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.


The level parameter is not valid, or the information in the buffer pointed to by the optval parameter is not valid.


The connection has timed out when SO_KEEPALIVE is set.


The option is unknown or unsupported for the specified provider or socket (see SO_GROUP_PRIORITY limitations).


The connection has been reset when SO_KEEPALIVE is set.


The descriptor is not a socket.



The setsockopt function sets the current value for a socket option associated with a socket of any type, in any state. Although options can exist at multiple protocol levels, they are always present at the uppermost socket level. Options affect socket operations, such as whether expedited data (OOB data for example) is received in the normal data stream, and whether broadcast messages can be sent on the socket.

Note  If the setsockopt function is called before the bind function, TCP/IP options will not be checked by using TCP/IP until the bind occurs. In this case, the setsockopt function call will always succeed, but the bind function call can fail because of an early setsockopt call failing.
Note  If a socket is opened, a setsockopt call is made, and then a sendto call is made, Windows Sockets performs an implicit bind function call.

There are two types of socket options: Boolean options that enable or disable a feature or behavior, and options that require an integer value or structure. To enable a Boolean option, the optval parameter points to a nonzero integer. To disable the option optval points to an integer equal to zero. The optlen parameter should be equal to sizeof(int) for Boolean options. For other options, optval points to an integer or structure that contains the desired value for the option, and optlen is the length of the integer or structure.

The following tables list some of the common options supported by the setsockopt function. The Type column identifies the type of data addressed by optval parameter. The Description column provides some basic information about the socket option. For more complete lists of socket options and more detailed information (default values, for example), see the detailed topics under Socket Options.

level = SOL_SOCKET

SO_BROADCASTBOOLConfigures a socket for sending broadcast data.
SO_CONDITIONAL_ACCEPTBOOLEnables incoming connections are to be accepted or rejected by the application, not by the protocol stack.
SO_DEBUGBOOLEnables debug output. Microsoft providers currently do not output any debug information.
SO_DONTLINGERBOOLDoes not block close waiting for unsent data to be sent. Setting this option is equivalent to setting SO_LINGER with l_onoff set to zero.
SO_DONTROUTEBOOLSets whether outgoing data should be sent on interface the socket is bound to and not a routed on some other interface. This option is not supported on ATM sockets (results in an error).
SO_KEEPALIVE BOOLEnables sending keep-alive packets for a socket connection. Not supported on ATM sockets (results in an error).
SO_LINGER LINGER Lingers on close if unsent data is present.
SO_OOBINLINEBOOLIndicates that out-of-bound data should be returned in-line with regular data. This option is only valid for connection-oriented protocols that support out-of-band data. For a discussion of this topic, see Protocol Independent Out-Of-band Data.
SO_RCVBUFintSpecifies the total per-socket buffer space reserved for receives.
SO_REUSEADDRBOOLAllows the socket to be bound to an address that is already in use. For more information, see bind. Not applicable on ATM sockets.
SO_EXCLUSIVEADDRUSE BOOLEnables a socket to be bound for exclusive access. Does not require administrative privilege.
SO_RCVTIMEODWORDSets the timeout, in milliseconds, for blocking receive calls.
SO_SNDBUFintSpecifies the total per-socket buffer space reserved for sends.
SO_SNDTIMEODWORDThe timeout, in milliseconds, for blocking send calls.
SO_UPDATE_ACCEPT_CONTEXTintUpdates the accepting socket with the context of the listening socket.
PVD_CONFIGService Provider DependentThis object stores the configuration information for the service provider associated with socket s. The exact format of this data structure is service provider specific.


For more complete and detailed information about socket options for level = SOL_SOCKET, see SOL_SOCKET Socket Options.


TCP_NODELAYBOOLDisables the Nagle algorithm for send coalescing.

This socket option is included for backward compatibility with Windows Sockets 1.1


For more complete and detailed information about socket options for level = IPPROTO_TCP, see IPPROTO_TCP Socket Options.


IPX_PTYPEintSets the IPX packet type.
IPX_FILTERPTYPEintSets the receive filter packet type
IPX_STOPFILTERPTYPEintStops filtering the filter type set with IPX_FILTERTYPE
IPX_DSTYPEintSets the value of the data stream field in the SPX header on every packet sent.
IPX_EXTENDED_ADDRESSBOOLSets whether extended addressing is enabled.
IPX_RECVHDRBOOLSets whether the protocol header is sent up on all receive headers.
IPX_RECEIVE_BROADCASTBOOLIndicates broadcast packets are likely on the socket. Set to TRUE by default. Applications that do not use broadcasts should set this to FALSE for better system performance.
IPX_IMMEDIATESPXACKBOOLDirects SPX connections not to delay before sending an ACK. Applications without back-and-forth traffic should set this to TRUE to increase performance.


For more complete and detailed information about socket options for level = NSPROTO_IPX, see NSPROTO_IPX Socket Options.

BSD options not supported for setsockopt are shown in the following table.

SO_ACCEPTCONNBOOLReturns whether a socket is in listening mode. This option is only Valid for connection-oriented protocols. This socket option is not supported for the setting.
SO_RCVLOWATintA socket option from BSD UNIX included for backward compatibility. This option sets the minimum number of bytes to process for socket input operations.
SO_SNDLOWATintA socket option from BSD UNIX included for backward compatibility. This option sets the minimum number of bytes to process for socket output operations.
SO_TYPEintReturns the socket type for the given socket (SOCK_STREAM or SOCK_DGRAM, for example This socket option is not supported for the setting the socket type.



Setting this socket option to TRUE delays the acknowledgment of a connection until after the WSAAccept condition function is called. If FALSE, the connection may be accepted before the condition function is called, but the connection will be disconnected if the condition function rejects the call. This option must be set before calling the listen function, otherwise WSAEINVAL is returned. SO_CONDITIONAL_ACCEPT is only supported for TCP and ATM.

TCP sets SO_CONDITIONAL_ACCEPT to FALSE by default, and therefore by default the connection will be accepted before the WSAAccept condition function is called. When set to TRUE, the conditional decision must be made within the TCP connection time-out. CF_DEFER connections are still subject to the time-out.



Windows Sockets service providers are encouraged (but not required) to supply output debug information if the SO_DEBUG option is set by an application. The mechanism for generating the debug information and the form it takes are beyond the scope of this document.


Reserved for future use with socket groups. Group priority indicates the relative priority of the specified socket relative to other sockets within the socket group. Values are nonnegative integers, with zero corresponding to the highest priority. Priority values represent a hint to the underlying service provider about how potentially scarce resources should be allocated. For example, whenever two or more sockets are both ready to transmit data, the highest priority socket (lowest value for SO_GROUP_PRIORITY) should be serviced first with the remainder serviced in turn according to their relative priorities.


An application can request that a TCP/IP provider enable the use of keep-alive packets on TCP connections by turning on the SO_KEEPALIVE socket option. A Windows Sockets provider need not support the use of keep-alives. If it does, the precise semantics are implementation-specific but should conform to section on the Requirements for Internet Hosts—Communication Layers specified in RFC 1122 available at the IETF website. (This resource may only be available in English.)

If a connection is dropped as the result of keep-alives the error code WSAENETRESET is returned to any calls in progress on the socket, and any subsequent calls will fail with WSAENOTCONN.

If keep-alive is enabled for a TCP socket with SO_KEEPALIVE, then the default TCP settings are used for the keep-alive timeout and interval unless these values have been changed by calling the WSAIoctl function with the SIO_KEEPALIVE_VALS option.


The SO_LINGER option controls the action taken when unsent data is queued on a socket and a closesocket is performed. See closesocket for a description of the way in which the SO_LINGER settings affect the semantics of closesocket. The application sets the desired behavior by creating a LINGER structure (pointed to by the optval parameter) with these members l_onoff and l_linger set appropriately.


By default, a socket cannot be bound (see bind) to a local address that is already in use. On occasion, however, it can be necessary to reuse an address in this way. Since every connection is uniquely identified by the combination of local and remote addresses, there is no problem with having two sockets bound to the same local address as long as the remote addresses are different. To inform the Windows Sockets provider that a bind on a socket should not be disallowed because the desired address is already in use by another socket, the application should set the SO_REUSEADDR socket option for the socket before issuing the bind. The option is interpreted only at the time of the bind. It is therefore unnecessary and harmless to set the option on a socket that is not to be bound to an existing address. Setting or resetting the option after the bind has no effect on this or any other socket.


When a Windows Sockets implementation supports the SO_RCVBUF and SO_SNDBUF options, an application can request different buffer sizes (larger or smaller). The call to setsockopt can succeed even when the implementation did not provide the whole amount requested. An application must call getsockopt with the same option to check the buffer size actually provided.


When using the recv function, if no data arrives during the period specified in SO_RCVTIMEO, the recv function completes. In Windows versions prior to Windows 2000, any data received subsequently fails with WSAETIMEDOUT. In Windows 2000 and later, if no data arrives within the period specified in SO_RCVTIMEO, the recv function returns WSAETIMEDOUT, and if data is received, recv returns SUCCESS.

If a send or receive operation times out on a socket, the socket state is indeterminate, and should not be used; TCP sockets in this state have a potential for data loss, since the operation could be canceled at the same moment the operation was to be completed.


This object stores the configuration information for the service provider associated with the socket specified in the s parameter. The exact format of this data structure is specific to each service provider.


The TCP_NODELAY option is specific to TCP/IP service providers. The Nagle algorithm is disabled if the TCP_NODELAY option is enabled (and vice versa). The process involves buffering send data when there is unacknowledged data already in flight or buffering send data until a full-size packet can be sent. It is highly recommended that TCP/IP service providers enable the Nagle Algorithm by default, and for the vast majority of application protocols the Nagle Algorithm can deliver significant performance enhancements. However, for some applications this algorithm can impede performance, and TCP_NODELAY can be used to turn it off. These are applications where many small messages are sent, and the time delays between the messages are maintained. Application writers should not set TCP_NODELAY unless the impact of doing so is well-understood and desired because setting TCP_NODELAY can have a significant negative impact on network and application performance.

Note  When issuing a blocking Winsock call such as setsockopt, Winsock may need to wait for a network event before the call can complete. Winsock performs an alertable wait in this situation, which can be interrupted by an asynchronous procedure call (APC) scheduled on the same thread. Issuing another blocking Winsock call inside an APC that interrupted an ongoing blocking Winsock call on the same thread will lead to undefined behavior, and must never be attempted by Winsock clients.

Example Code

The following example demonstrates the setsockopt function.

#ifndef UNICODE
#define UNICODE


#include <winsock2.h>
#include <Ws2tcpip.h>
#include <stdio.h>

// Link with ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")

int main()

    // Declare variables
    WSADATA wsaData;

    SOCKET ListenSocket;
    sockaddr_in service;

    int iResult = 0;

    BOOL bOptVal = FALSE;
    int bOptLen = sizeof (BOOL);

    int iOptVal = 0;
    int iOptLen = sizeof (int);

    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != NO_ERROR) {
        wprintf(L"Error at WSAStartup()\n");
        return 1;
    // Create a listening socket
    ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (ListenSocket == INVALID_SOCKET) {
        wprintf(L"socket function failed with error: %u\n", WSAGetLastError());
        return 1;
    // Bind the socket to the local IP address
    // and port 27015
    hostent *thisHost;
    char *ip;
    u_short port;
    port = 27015;
    thisHost = gethostbyname("");
    ip = inet_ntoa(*(struct in_addr *) *thisHost->h_addr_list);

    service.sin_family = AF_INET;
    service.sin_addr.s_addr = inet_addr(ip);
    service.sin_port = htons(port);

    iResult = bind(ListenSocket, (SOCKADDR *) & service, sizeof (service));
    if (iResult == SOCKET_ERROR) {
        wprintf(L"bind failed with error %u\n", WSAGetLastError());
        return 1;
    // Initialize variables and call setsockopt. 
    // The SO_KEEPALIVE parameter is a socket option 
    // that makes the socket send keepalive messages
    // on the session. The SO_KEEPALIVE socket option
    // requires a boolean value to be passed to the
    // setsockopt function. If TRUE, the socket is
    // configured to send keepalive messages, if FALSE
    // the socket configured to NOT send keepalive messages.
    // This section of code tests the setsockopt function
    // by checking the status of SO_KEEPALIVE on the socket
    // using the getsockopt function.

    bOptVal = TRUE;

    iResult = getsockopt(ListenSocket, SOL_SOCKET, SO_KEEPALIVE, (char *) &iOptVal, &iOptLen);
    if (iResult == SOCKET_ERROR) {
        wprintf(L"getsockopt for SO_KEEPALIVE failed with error: %u\n", WSAGetLastError());
    } else
        wprintf(L"SO_KEEPALIVE Value: %ld\n", iOptVal);

    iResult = setsockopt(ListenSocket, SOL_SOCKET, SO_KEEPALIVE, (char *) &bOptVal, bOptLen);
    if (iResult == SOCKET_ERROR) {
        wprintf(L"setsockopt for SO_KEEPALIVE failed with error: %u\n", WSAGetLastError());
    } else
        wprintf(L"Set SO_KEEPALIVE: ON\n");

    iResult = getsockopt(ListenSocket, SOL_SOCKET, SO_KEEPALIVE, (char *) &iOptVal, &iOptLen);
    if (iResult == SOCKET_ERROR) {
        wprintf(L"getsockopt for SO_KEEPALIVE failed with error: %u\n", WSAGetLastError());
    } else
        wprintf(L"SO_KEEPALIVE Value: %ld\n", iOptVal);

    return 0;

Notes for IrDA Sockets

When developing applications using Windows sockets for IrDA, note the following:

  • The Af_irda.h header file must be explicitly included.
  • IrDA provides the following socket option:
    IRLMP_IAS_SET*IAS_SETSets IAS attributes


The IRLMP_IAS_SET socket option enables the application to set a single attribute of a single class in the local IAS. The application specifies the class to set, the attribute, and attribute type. The application is expected to allocate a buffer of the necessary size for the passed parameters.

IrDA provides an IAS database that stores IrDA-based information. Limited access to the IAS database is available through the Windows Sockets 2 interface, but such access is not normally used by applications, and exists primarily to support connections to non-Windows devices that are not compliant with the Windows Sockets 2 IrDA conventions.

The following structure, IAS_SET, is used with the IRLMP_IAS_SET setsockopt option to manage the local IAS database:

// #include <Af_irda.h> for this struct

typedef struct _IAS_SET {
    u_char      irdaClassName[IAS_MAX_CLASSNAME];
    char      irdaAttribName[IAS_MAX_ATTRIBNAME];
    u_long    irdaAttribType;
              LONG irdaAttribInt;
                   u_long   Len;
                   u_char    OctetSeq[IAS_MAX_OCTET_STRING];
              } irdaAttribOctetSeq;
                   u_long    Len;
                   u_long    CharSet;
                   u_char    UsrStr[IAS_MAX_USER_STRING];
              } irdaAttribUsrStr;
    } irdaAttribute;

The following structure, IAS_QUERY, is used with the IRLMP_IAS_QUERY setsockopt option to query a peer's IAS database:

// #include <Af_irda.h> for this struct

typedef struct _WINDOWS_IAS_QUERY {
        u_char   irdaDeviceID[4];
        char     irdaClassName[IAS_MAX_CLASSNAME];
        char     irdaAttribName[IAS_MAX_ATTRIBNAME];
        u_long   irdaAttribType;
                  LONG    irdaAttribInt;
                          u_long  Len;
                          u_char  OctetSeq[IAS_MAX_OCTET_STRING];
                  } irdaAttribOctetSeq;
                          u_long  Len;
                          u_long  CharSet;
                          u_char  UsrStr[IAS_MAX_USER_STRING];
                  } irdaAttribUsrStr;
        } irdaAttribute;

Many SO_ level socket options are not meaningful to IrDA. Only SO_LINGER is specifically supported.

Windows Phone 8: This function is supported for Windows Phone Store apps on Windows Phone 8 and later.

Windows 8.1 and Windows Server 2012 R2: This function is supported for Windows Store apps on Windows 8.1, Windows Server 2012 R2, and later.


Minimum supported client

Windows 8.1, Windows Vista [desktop apps | UWP apps]

Minimum supported server

Windows Server 2003 [desktop apps | UWP apps]

Minimum supported phone

Windows Phone 8







See also

IPPROTO_IP Socket Options
IPPROTO_IPV6 Socket Options
IPPROTO_RM Socket Options
IPPROTO_TCP Socket Options
IPPROTO_UDP Socket Options
NSPROTO_IPX Socket Options
Socket Options
SOL_APPLETALK Socket Options
SOL_IRLMP Socket Options
SOL_SOCKET Socket Options
Winsock Functions



© 2018 Microsoft