Remarks
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 with 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 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 options are supported for setsockopt. For default values of these options, see the description. The Type identifies the type of data addressed by optval.
For more information on socket options, see Socket Options.
level = SOL_SOCKET
Value Type Meaning
SO_BROADCAST BOOL Enables transmission and receipt of broadcast messages on the socket.
SO_CONDITIONAL_ACCEPT BOOL Enables sockets to delay the acknowledgment of a connection until after the WSAAccept condition function is called.
SO_DEBUG BOOL Records debugging information.
SO_DONTLINGER BOOL Does 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_DONTROUTE BOOL Disable routing: send directly to an interface. When this option is set, it succeeds but is ignored for both AF_INET and AF_INET6 sockets. This option is not supported on ATM sockets (results in an error).
SO_GROUP_PRIORITY int Reserved.
SO_KEEPALIVE BOOL Sends keep-alives. Not supported on ATM sockets (results in an error).
SO_LINGER LINGER Lingers on close if unsent data is present.
SO_OOBINLINE BOOL Receives OOB data in the normal data stream. (See section Protocol Independent Out-Of-band Data for a discussion of this topic.)
SO_RCVBUF int Specifies the total per-socket buffer space reserved for receives. This is unrelated to SO_MAX_MSG_SIZE and does not necessarily correspond to the size of the TCP receive window.
SO_REUSEADDR BOOL Allows the socket to be bound to an address that is already in use. (See bind.) Not applicable on ATM sockets.
SO_EXCLUSIVEADDRUSE BOOL Enables a socket to be bound for exclusive access. Does not require administrative privilege.
SO_SNDBUF int Specifies the total per-socket buffer space reserved for sends. This is unrelated to SO_MAX_MSG_SIZE and does not necessarily correspond to the size of a TCP send window..
SO_UPDATE_ACCEPT_CONTEXT int Updates the accepting socket with the context of the listening socket.
PVD_CONFIG Service Provider Dependent This object stores the configuration information for the service provider associated with socket s. The exact format of this data structure is service provider specific.
level = IPPROTO_TCP
Value Type Meaning
TCP_NODELAY BOOL Disables the Nagle algorithm for send coalescing.
This socket option is included for backward compatibility with Windows Sockets 1.1
level = NSPROTO_IPX
Note Windows NT supports all IPX options. Windows Me/98/95 support only the following options:
IPX_PTYPE
IPX_FILTERPTYPE
IPX_DSTYPE
IPX_RECVHDR
IPX_MAXSIZE (used with the getsockopt function)
IPX_ADDRESS (used with the getsockopt function)
Value Type Meaning
IPX_PTYPE int Sets the IPX packet type.
IPX_FILTERPTYPE int Sets the receive filter packet type
IPX_STOPFILTERPTYPE int Stops filtering the filter type set with IPX_FILTERTYPE
IPX_DSTYPE int Sets the value of the data stream field in the SPX header on every packet sent.
IPX_EXTENDED_ADDRESS BOOL Sets whether extended addressing is enabled.
IPX_RECVHDR BOOL Sets whether the protocol header is sent up on all receive headers.
IPX_RECEIVE_BROADCAST BOOL Indicates 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_IMMEDIATESPXACK BOOL Directs SPX connections not to delay before sending an ACK. Applications without back-and-forth traffic should set this to TRUE to increase performance.
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
);
Parameters
s
A descriptor that identifies a socket.
level
The level at which the option is defined (for example, SOL_SOCKET).
optname
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
A pointer to the buffer in which the value for the requested option is specified.
optlen
The size, in bytes, of the optval buffer.
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 code Meaning
WSANOTINITIALISED
A successful WSAStartup call must occur before using this function.
WSAENETDOWN
The network subsystem has failed.
WSAEFAULT
The optval parameter is not in a valid part of the process address space or the optlen parameter is too small.
WSAEINPROGRESS
A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.
WSAEINVAL
The level parameter is not valid, or the information in optval parameter is not valid.
WSAENETRESET
The connection has timed out when SO_KEEPALIVE is set.
WSAENOPROTOOPT
The option is unknown or unsupported for the specified provider or socket (see SO_GROUP_PRIORITY limitations).
WSAENOTCONN
The connection has been reset when SO_KEEPALIVE is set.
WSAENOTSOCK
The descriptor is not a socket.
Example Code
The following example demonstrates the setsockopt function.
#include <stdio.h>
#include "winsock2.h"
void main() {
//---------------------------------------
// Declare variables
WSADATA wsaData;
SOCKET ListenSocket;
sockaddr_in service;
//---------------------------------------
// Initialize Winsock
int iResult = WSAStartup( MAKEWORD(2,2), &wsaData );
if( iResult != NO_ERROR )
printf("Error at WSAStartup\n");
//---------------------------------------
// Create a listening socket
ListenSocket = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
if (ListenSocket == INVALID_SOCKET) {
printf("Error at socket()\n");
WSACleanup();
return;
}
//---------------------------------------
// 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);
if ( bind( ListenSocket,(SOCKADDR*) &service, sizeof(service) ) == SOCKET_ERROR ) {
printf("bind failed\n");
closesocket(ListenSocket);
return;
}
//---------------------------------------
// 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.
BOOL bOptVal = TRUE;
int bOptLen = sizeof(BOOL);
int iOptVal;
int iOptLen = sizeof(int);
if (getsockopt(ListenSocket, SOL_SOCKET, SO_KEEPALIVE, (char*)&iOptVal, &iOptLen) != SOCKET_ERROR) {
printf("SO_KEEPALIVE Value: %ld\n", iOptVal);
}
if (setsockopt(ListenSocket, SOL_SOCKET, SO_KEEPALIVE, (char*)&bOptVal, bOptLen) != SOCKET_ERROR) {
printf("Set SO_KEEPALIVE: ON\n");
}
if (getsockopt(ListenSocket, SOL_SOCKET, SO_KEEPALIVE, (char*)&iOptVal, &iOptLen) != SOCKET_ERROR) {
printf("SO_KEEPALIVE Value: %ld\n", iOptVal);
}
WSACleanup();
return;
}
Notes for IrDA Sockets
Keep in mind the following:
The Af_irda.h header file must be explicitly included.
IrDA provides the following socket option:Value Type Meaning
IRLMP_IAS_SET *IAS_SET Sets 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:
typedef struct _IAS_SET {
char irdaClassName[IAS_MAX_CLASSNAME];
char irdaAttribName[IAS_MAX_ATTRIBNAME];
u_long irdaAttribType;
union
{
LONG irdaAttribInt;
struct
{
u_short Len;
u_char OctetSeq[IAS_MAX_OCTET_STRING];
} irdaAttribOctetSeq;
struct
{
u_char Len;
u_char CharSet;
u_char UsrStr[IAS_MAX_USER_STRING];
} irdaAttribUsrStr;
} irdaAttribute;
} IAS_SET, *PIAS_SET, FAR *LPIAS_SET;
The following structure, IAS_QUERY, is used with the IRLMP_IAS_QUERY setsockopt option to query a peer's IAS database:
typedef struct _WINDOWS_IAS_QUERY {
u_char irdaDeviceID[4];
char irdaClassName[IAS_MAX_CLASSNAME];
char irdaAttribName[IAS_MAX_ATTRIBNAME];
u_long irdaAttribType;
union
{
LONG irdaAttribInt;
struct
{
u_long Len;
u_char OctetSeq[IAS_MAX_OCTET_STRING];
} irdaAttribOctetSeq;
struct
{
u_long Len;
u_long CharSet;
u_char UsrStr[IAS_MAX_USER_STRING];
} irdaAttribUsrStr;
} irdaAttribute;
} IAS_QUERY, *PIAS_QUERY, FAR *LPIAS_QUERY;
Many SO_ level socket options are not meaningful to IrDA. Only SO_LINGER is specifically supported.
Note setsockopt must be called before bind on Windows NT 4.0, Windows 95, and Windows 98 platforms.
Requirements
Client
Requires Windows Vista, Windows XP, Windows 2000 Professional, Windows NT Workstation, Windows Me, Windows 98, or Windows 95.
Server
Requires Windows Server 2008, Windows Server 2003, Windows 2000 Server, or Windows NT Server.
Header
Declared in Winsock2.h.
Library
Use Ws2_32.lib.
DLL
Requires Ws2_32.dll.