有些情况下,我们需要对Socket行为和属性进一步控制,例如修改缓冲区大小,查看Socket状态,这就需要设置/获取Socket选项。
1、获取Socket选项int getsockopt(SOCKET s,int level,int optname,void *optval,int *optlen)
s
:Socket描述符level
:选项级别,包括SOL_SOCKET
和IPPROTO_TCP
optname
:Socket选项的名字optval
:用于接收Socket数值的缓冲区optlen
:缓冲区大小
例如:
int optVal;
int optLen=sizeof(optVal);
// getsocketopt
getsockopt(ListenSocket,SOL_SOCKET,SO_ACCEPTCONN,(char*)&optVal,&optLen);
cout<<"SO_ACCEPTCONN:"<<optVal<<endl;
2、设置Socket选项int setsockopt(SOCKET s,int level,int optname,void *optval,int optlen)
s
:Socket描述符level
:选项级别,包括SOL_SOCKET
和IPPROTO_TCP
optname
:Socket选项的名字optval
:用于设置Socket数值的缓冲区optlen
:缓冲区大小
例如:
bool bopt=true;
int boptLen=sizeof(bopt);
// 修改前
getsockopt(ListenSocket,SOL_SOCKET,SO_KEEPALIVE,(char*)&optVal,&optLen);
cout<<"SO_KEEPALIVE:"<<optVal<<endl;
// setsockopt
setsockopt(ListenSocket,SOL_SOCKET,SO_KEEPALIVE,(char*)&bopt,boptLen);
// 修改后
getsockopt(ListenSocket,SOL_SOCKET,SO_KEEPALIVE,(char*)&optVal,&optLen);
cout<<"SO_KEEPALIVE:"<<optVal<<endl;