In some cases, we need to further control the socket behavior and attributes, such as modifying the buffer size and viewing the socket status. Therefore, we need to set/obtain the socket options.
1. Obtain socket options
int getsockopt(SOCKET s,int level,int optname,void *optval,int *optlen)
s
: Socket Descriptor
level
: Option level, includingSOL_SOCKET
AndIPPROTO_TCP
optname
: Socket option name
optval
: Buffer Used to receive socket values
optlen
: Buffer size
For example:
int optVal;int optLen=sizeof(optVal);// getsocketoptgetsockopt(ListenSocket,SOL_SOCKET,SO_ACCEPTCONN,(char*)&optVal,&optLen);cout<<"SO_ACCEPTCONN:"<<optVal<<endl;
2. Set socket options
int setsockopt(SOCKET s,int level,int optname,void *optval,int optlen)
s
: Socket Descriptor
level
: Option level, includingSOL_SOCKET
AndIPPROTO_TCP
optname
: Socket option name
optval
: Buffer used to set the socket Value
optlen
: Buffer size
For example:
Bool bopt = true; int boptlen = sizeof (bopt); // getsockopt (listensocket, sol_socket, so_keepalive, (char *) & optval, & optlen) before modification ); cout <"so_keepalive:" <optval <Endl; // setsockoptsetsockopt (listensocket, sol_socket, so_keepalive, (char *) & bopt, boptlen ); // getsockopt (listensocket, sol_socket, so_keepalive, (char *) & optval, & optlen); cout <"so_keepalive:" <optval <Endl;
Socket programming basics-socket options