From ebaa51c8f5b4b6c0473799a3c1d5727c0b0a040d Mon Sep 17 00:00:00 2001 From: Kiritow <1362050620@qq.com> Date: Thu, 17 May 2018 19:38:40 +0800 Subject: [PATCH] Fix serversock::set_reuse() --- gsock.cpp | 45 +++++++++++++++++++++++++++++++++------------ gsock.h | 2 ++ 2 files changed, 35 insertions(+), 12 deletions(-) diff --git a/gsock.cpp b/gsock.cpp index 324d662..718d7b3 100644 --- a/gsock.cpp +++ b/gsock.cpp @@ -249,22 +249,37 @@ int sock::getpeer(std::string& IPStr,int& Port) 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) { myliblog("serversock::bind() %p\n",this); - 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; + if (!_vp->created) + { + int ret = _impl::create_socket(_vp); + if (ret < 0) + return ret; + } sockaddr_in saddr; @@ -277,6 +292,12 @@ int serversock::bind(int Port) int serversock::set_reuse() { + if (!_vp->created) + { + int ret = _impl::create_socket(_vp); + if (ret < 0) + return ret; + } socklen_t opt=1; return setsockopt(_vp->sfd,SOL_SOCKET,SO_REUSEADDR,(const char*)&opt,sizeof(opt)); } diff --git a/gsock.h b/gsock.h index bbcfa83..52c2a50 100644 --- a/gsock.h +++ b/gsock.h @@ -83,6 +83,8 @@ public: /// -1: accept() call error. See errno. /// -2: _out_s is a connected socket, which should not be passed in. int accept(sock& _out_s); +private: + struct _impl; }; class udpsock : public vsock