Fix serversock::set_reuse()

This commit is contained in:
Kirigaya Kazuto 2018-05-17 19:38:40 +08:00
parent d44dbebe13
commit ebaa51c8f5
2 changed files with 35 additions and 12 deletions

View File

@ -249,22 +249,37 @@ int sock::getpeer(std::string& IPStr,int& Port)
return _sock_getname_call(_vp->sfd,IPStr,Port,getpeername); return _sock_getname_call(_vp->sfd,IPStr,Port,getpeername);
} }
struct serversock::_impl
{
public:
static int create_socket(vsock::_impl* _vp)
{
if (_vp->created)
{
return -2;
}
_vp->sfd = socket(AF_INET, SOCK_STREAM, 0);
if (_vp->sfd<0)
{
myliblog("socket() returns %d. WSAGetLastError: %d\n", _vp->sfd, WSAGetLastError());
return -3;
}
myliblog("Socket created: [%d] in %p\n", _vp->sfd, this);
_vp->created = true;
return 0;
}
};
int serversock::bind(int Port) int serversock::bind(int Port)
{ {
myliblog("serversock::bind() %p\n",this); myliblog("serversock::bind() %p\n",this);
if(_vp->created) if (!_vp->created)
{ {
return -2; int ret = _impl::create_socket(_vp);
} if (ret < 0)
_vp->sfd=socket(AF_INET,SOCK_STREAM,0); return ret;
if(_vp->sfd<0) }
{
myliblog("socket() returns %d. WSAGetLastError: %d\n",_vp->sfd,WSAGetLastError());
return -3;
}
myliblog("Socket created: [%d] in %p\n",_vp->sfd,this);
_vp->created=true;
sockaddr_in saddr; sockaddr_in saddr;
@ -277,6 +292,12 @@ int serversock::bind(int Port)
int serversock::set_reuse() int serversock::set_reuse()
{ {
if (!_vp->created)
{
int ret = _impl::create_socket(_vp);
if (ret < 0)
return ret;
}
socklen_t opt=1; socklen_t opt=1;
return setsockopt(_vp->sfd,SOL_SOCKET,SO_REUSEADDR,(const char*)&opt,sizeof(opt)); return setsockopt(_vp->sfd,SOL_SOCKET,SO_REUSEADDR,(const char*)&opt,sizeof(opt));
} }

View File

@ -83,6 +83,8 @@ public:
/// -1: accept() call error. See errno. /// -1: accept() call error. See errno.
/// -2: _out_s is a connected socket, which should not be passed in. /// -2: _out_s is a connected socket, which should not be passed in.
int accept(sock& _out_s); int accept(sock& _out_s);
private:
struct _impl;
}; };
class udpsock : public vsock class udpsock : public vsock