setsockopt函数使用

int setsockopt (
SOCKET s,                 
int level,                
int optname,              
const char FAR * optval, 
int optlen                
);

The Windows Sockets setsockopt function sets a socket option.

中文解释好像是:设置套接字的选项。

先看如下代码:
setsockopt(SockRaw,IPPROTO_IP,IP_HDRINCL,(char *)&flag,sizeof(int))

这里是设置SockRaw这个套接字的ip选项中的IP_HDRINCL

参考以下资料:

***************************************************************************************************

Linux网络编程--8. 套接字选项 
有时候我们要控制套接字的行为(如修改缓冲区的大小),这个时候我们就要控制套接字的选项了. 


8.1 getsockopt和setsockopt 

int getsockopt(int sockfd,int level,int optname,void *optval,socklen_t *optlen) 
int setsockopt(int sockfd,int level,int optname,const void *optval,socklen_t *optlen)

level指定控制套接字的层次.可以取三种值: 
1)SOL_SOCKET:通用套接字选项. 
2)IPPROTO_IP:IP选项. 
3)IPPROTO_TCP:TCP选项. 
optname指定控制的方式(选项的名称),我们下面详细解释 

optval获得或者是设置套接字选项.根据选项名称的数据类型进行转换 


选项名称        说明                  数据类型 
========================================================================
            SOL_SOCKET 
------------------------------------------------------------------------ 
SO_BROADCAST      允许发送广播数据            int 
SO_DEBUG        允许调试                int 
SO_DONTROUTE      不查找路由               int 
SO_ERROR        获得套接字错误             int 
SO_KEEPALIVE      保持连接                int 
SO_LINGER        延迟关闭连接              struct linger 
SO_OOBINLINE      带外数据放入正常数据流         int 
SO_RCVBUF        接收缓冲区大小             int 
SO_SNDBUF        发送缓冲区大小             int 
SO_RCVLOWAT       接收缓冲区下限             int 
SO_SNDLOWAT       发送缓冲区下限             int 
SO_RCVTIMEO       接收超时                struct timeval 
SO_SNDTIMEO       发送超时                struct timeval 
SO_REUSERADDR      允许重用本地地址和端口         int 
SO_TYPE         获得套接字类型             int 
SO_BSDCOMPAT      与BSD系统兼容              int 
==========================================================================
            IPPROTO_IP 
-------------------------------------------------------------------------- 
IP_HDRINCL       在数据包中包含IP首部          int 
IP_OPTINOS       IP首部选项               int 
IP_TOS         服务类型 
IP_TTL         生存时间                int 
==========================================================================
            IPPRO_TCP 
-------------------------------------------------------------------------- 
TCP_MAXSEG       TCP最大数据段的大小           int 
TCP_NODELAY       不使用Nagle算法             int 
=========================================================================

setsockopt设置SO_REUSEADDR。

socket关闭之后并不会立即收回,而是要经历一个TIME_WAIT的阶段。windows下最多可以达到4分钟。

所以在这个时候对这个端口进行重新绑定就会出错。所以需要先设置 SO_REUSEADDR.

或者在closesocket的时候,使用setsockopt设置SO_DONTLINGER。也不会有TIME_WAIT的阶段.

通常使用这个设置来加强网络程序的健壮性。

下面是别处补充的资料:1.closesocket(一般不会立即关闭而经历TIME_WAIT的过程)后想继续重用该socket:
BOOL bReuseaddr=TRUE;
setsockopt(s,SOL_SOCKET ,SO_REUSEADDR,(const char*)&bReuseaddr,sizeof(BOOL));


2. 如果要已经处于连接状态的soket在调用closesocket后强制关闭,不经历
TIME_WAIT的过程:
BOOL bDontLinger = FALSE;
setsockopt(s,SOL_SOCKET,SO_DONTLINGER,(const char*)&bDontLinger,sizeof(BOOL));


3.在send(),recv()过程中有时由于网络状况等原因,发收不能预期进行,而设置收发时限:
int nNetTimeout=1000;//1秒
//发送时限
setsockopt(socket,SOL_S0CKET,SO_SNDTIMEO,(char *)&nNetTimeout,sizeof(int));
//接收时限
setsockopt(socket,SOL_S0CKET,SO_RCVTIMEO,(char *)&nNetTimeout,sizeof(int));


4.在send()的时候,返回的是实际发送出去的字节(同步)或发送到socket缓冲区的字节
(异步);系统默认的状态发送和接收一次为8688字节(约为8.5K);在实际的过程中发送数据
和接收数据量比较大,可以设置socket缓冲区,而避免了send(),recv()不断的循环收发:
// 接收缓冲区
int nRecvBuf=32*1024;//设置为32K
setsockopt(s,SOL_SOCKET,SO_RCVBUF,(const char*)&nRecvBuf,sizeof(int));
//发送缓冲区
int nSendBuf=32*1024;//设置为32K
setsockopt(s,SOL_SOCKET,SO_SNDBUF,(const char*)&nSendBuf,sizeof(int));


5. 如果在发送数据的时,希望不经历由系统缓冲区到socket缓冲区的拷贝而影响
程序的性能:
int nZero=0;
setsockopt(socket,SOL_S0CKET,SO_SNDBUF,(char *)&nZero,sizeof(nZero));


6.同上在recv()完成上述功能(默认情况是将socket缓冲区的内容拷贝到系统缓冲区):
int nZero=0;
setsockopt(socket,SOL_S0CKET,SO_RCVBUF,(char *)&nZero,sizeof(int));


7.一般在发送UDP数据报的时候,希望该socket发送的数据具有广播特性:
BOOL bBroadcast=TRUE;
setsockopt(s,SOL_SOCKET,SO_BROADCAST,(const char*)&bBroadcast,sizeof(BOOL));


8.在client连接服务器过程中,如果处于非阻塞模式下的socket在connect()的过程中可
以设置connect()延时,直到accpet()被呼叫(本函数设置只有在非阻塞的过程中有显著的
作用,在阻塞的函数调用中作用不大)
BOOL bConditionalAccept=TRUE;
setsockopt(s,SOL_SOCKET,SO_CONDITIONAL_ACCEPT,(const char*)&bConditionalAccept,sizeof(BOOL));


9.如果在发送数据的过程中(send()没有完成,还有数据没发送)而调用了closesocket(),以前我们
一般采取的措施是"从容关闭"shutdown(s,SD_BOTH),但是数据是肯定丢失了,如何设置让程序满足具体
应用的要求(即让没发完的数据发送出去后在关闭socket)?
struct linger {
u_short l_onoff;
u_short l_linger;
};
linger m_sLinger;
m_sLinger.l_onoff=1;//(在closesocket()调用,但是还有数据没发送完毕的时候容许逗留)
// 如果m_sLinger.l_onoff=0;则功能和2.)作用相同;
m_sLinger.l_linger=5;//(容许逗留的时间为5秒)
setsockopt(s,SOL_SOCKET,SO_LINGER,(const char*)&m_sLinger,sizeof(linger)); 

man setsockopt 查看的官方使用帮助:

SETSOCKOPT(P)                                                                                                                                                                            SETSOCKOPT(P)

NAME
       setsockopt - set the socket options

SYNOPSIS
       #include <sys/socket.h>

       int setsockopt(int socket, int level, int option_name,
              const void *option_value, socklen_t option_len);

DESCRIPTION
       The setsockopt() function shall set the option specified by the option_name argument, at the protocol level specified by the level argument, to the value pointed to by the option_value argu-
       ment for the socket associated with the file descriptor specified by the socket argument.

       The level argument specifies the protocol level at which the option resides. To set options at the socket level, specify the level argument as SOL_SOCKET. To set options at other levels, sup-
       ply the appropriate level identifier for the protocol controlling the option. For example, to indicate that an option is interpreted by the TCP (Transport Control Protocol), set level to
       IPPROTO_TCP as defined in the <netinet/in.h> header.

       The option_name argument specifies a single option to set. The option_name argument and any specified options are passed uninterpreted to the appropriate protocol module for interpretations.
       The <sys/socket.h> header defines the socket-level options. The options are as follows:

       SO_DEBUG
              Turns on recording of debugging information. This option enables or disables debugging in the underlying protocol modules. This option takes an int value. This is a Boolean option.

       SO_BROADCAST
              Permits sending of broadcast messages, if this is supported by the protocol. This option takes an int value. This is a Boolean option.

       SO_REUSEADDR
              Specifies that the rules used in validating addresses supplied to bind() should allow reuse of local addresses, if this is supported by the protocol. This option takes an int value.
              This is a Boolean option.

       SO_KEEPALIVE
              Keeps connections active by enabling the periodic transmission of messages, if this is supported by the protocol. This option takes an int value.

       If the connected socket fails to respond to these messages, the connection is broken and threads writing to that socket are notified with a SIGPIPE signal. This is a Boolean option.

       SO_LINGER
              Lingers on a close() if data is present. This option controls the action taken when unsent messages queue on a socket and close() is performed. If SO_LINGER is set, the system shall
              block the process during close() until it can transmit the data or until the time expires. If SO_LINGER is not specified, and close() is issued, the system handles the call in a way
              that allows the process to continue as quickly as possible. This option takes a linger structure, as defined in the <sys/socket.h> header, to specify the state of the option and linger
              interval.

       SO_OOBINLINE
              Leaves received out-of-band data (data marked urgent) inline. This option takes an int value. This is a Boolean option.

       SO_SNDBUF
SETSOCKOPT(P)                                                                                                                                                                            SETSOCKOPT(P)

NAME
       setsockopt - set the socket options

SYNOPSIS
       #include <sys/socket.h>

       int setsockopt(int socket, int level, int option_name,
              const void *option_value, socklen_t option_len);

DESCRIPTION
       The setsockopt() function shall set the option specified by the option_name argument, at the protocol level specified by the level argument, to the value pointed to by the option_value argu-
       ment for the socket associated with the file descriptor specified by the socket argument.

       The level argument specifies the protocol level at which the option resides. To set options at the socket level, specify the level argument as SOL_SOCKET. To set options at other levels, sup-
       ply the appropriate level identifier for the protocol controlling the option. For example, to indicate that an option is interpreted by the TCP (Transport Control Protocol), set level to
       IPPROTO_TCP as defined in the <netinet/in.h> header.

       The option_name argument specifies a single option to set. The option_name argument and any specified options are passed uninterpreted to the appropriate protocol module for interpretations.
       The <sys/socket.h> header defines the socket-level options. The options are as follows:

       SO_DEBUG
              Turns on recording of debugging information. This option enables or disables debugging in the underlying protocol modules. This option takes an int value. This is a Boolean option.

       SO_BROADCAST
              Permits sending of broadcast messages, if this is supported by the protocol. This option takes an int value. This is a Boolean option.

       SO_REUSEADDR
              Specifies that the rules used in validating addresses supplied to bind() should allow reuse of local addresses, if this is supported by the protocol. This option takes an int value.
              This is a Boolean option.

       SO_KEEPALIVE
              Keeps connections active by enabling the periodic transmission of messages, if this is supported by the protocol. This option takes an int value.

       If the connected socket fails to respond to these messages, the connection is broken and threads writing to that socket are notified with a SIGPIPE signal. This is a Boolean option.

       SO_LINGER
              Lingers on a close() if data is present. This option controls the action taken when unsent messages queue on a socket and close() is performed. If SO_LINGER is set, the system shall
              block the process during close() until it can transmit the data or until the time expires. If SO_LINGER is not specified, and close() is issued, the system handles the call in a way
              that allows the process to continue as quickly as possible. This option takes a linger structure, as defined in the <sys/socket.h> header, to specify the state of the option and linger
              interval.

       SO_OOBINLINE
              Leaves received out-of-band data (data marked urgent) inline. This option takes an int value. This is a Boolean option.

       SO_SNDBUF
              Sets send buffer size. This option takes an int value.

       SO_RCVBUF
              Sets receive buffer size. This option takes an int value.

       SO_DONTROUTE
              Requests that outgoing messages bypass the standard routing facilities. The destination shall be on a directly-connected network, and messages are directed to the appropriate network
              interface according to the destination address. The effect, if any, of this option depends on what protocol is in use. This option takes an int value. This is a Boolean option.

       SO_RCVLOWAT
              Sets the minimum number of bytes to process for socket input operations. The default value for SO_RCVLOWAT is 1. If SO_RCVLOWAT is set to a larger value, blocking receive calls nor-
              mally wait until they have received the smaller of the low water mark value or the requested amount. (They may return less than the low water mark if an error occurs, a signal is
              caught, or the type of data next in the receive queue is different from that returned; for example, out-of-band data.) This option takes an int value. Note that not all implementa-
              tions allow this option to be set.

       SO_RCVTIMEO
              Sets the timeout value that specifies the maximum amount of time an input function waits until it completes. It accepts a timeval structure with the number of seconds and microseconds
              specifying the limit on how long to wait for an input operation to complete. If a receive operation has blocked for this much time without receiving additional data, it shall return
              with a partial count or errno set to [EAGAIN] or [EWOULDBLOCK] if no data is received. The default for this option is zero, which indicates that a receive operation shall not time out.
              This option takes a timeval structure. Note that not all implementations allow this option to be set.

       SO_SNDLOWAT
              Sets the minimum number of bytes to process for socket output operations. Non-blocking output operations shall process no data if flow control does not allow the smaller of the send
              low water mark value or the entire request to be processed. This option takes an int value. Note that not all implementations allow this option to be set.

       SO_SNDTIMEO
              Sets the timeout value specifying the amount of time that an output function blocks because flow control prevents data from being sent. If a send operation has blocked for this time,
              it shall return with a partial count or with errno set to [EAGAIN] or [EWOULDBLOCK] if no data is sent. The default for this option is zero, which indicates that a send operation shall
              not time out. This option stores a timeval structure. Note that not all implementations allow this option to be set.

       For Boolean options, 0 indicates that the option is disabled and 1 indicates that the option is enabled.

       Options at other protocol levels vary in format and name.

RETURN VALUE
       Upon successful completion, setsockopt() shall return 0. Otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS
       The setsockopt() function shall fail if:

       EBADF The socket argument is not a valid file descriptor.

       EDOM   The send and receive timeout values are too big to fit into the timeout fields in the socket structure.

       EINVAL The specified option is invalid at the specified socket level or the socket has been shut down.

       EISCONN
              The socket is already connected, and a specified option cannot be set while the socket is connected.

       ENOPROTOOPT

              The option is not supported by the protocol.

       ENOTSOCK
              The socket argument does not refer to a socket.

       The setsockopt() function may fail if:

       ENOMEM There was insufficient memory available for the operation to complete.

       ENOBUFS
              Insufficient resources are available in the system to complete the call.

       The following sections are informative.

EXAMPLES
       None.

APPLICATION USAGE
       The setsockopt() function provides an application program with the means to control socket behavior. An application program can use setsockopt() to allocate buffer space, control timeouts, or
       permit socket data broadcasts. The <sys/socket.h> header defines the socket-level options available to setsockopt().

       Options may exist at multiple protocol levels. The SO_ options are always present at the uppermost socket level.




转自:http://hi.baidu.com/yelangdefendou/item/74161d0f384abd3c4ac4a316

你可能感兴趣的:(setsockopt函数使用)