From eb2337ae222d106aa8c07550f621caef4afc3286 Mon Sep 17 00:00:00 2001 From: Kiritow-Tablet <1362050620@qq.com> Date: Fri, 4 May 2018 18:04:29 +0800 Subject: [PATCH] Fix bug in getlocal(),getpeer(). --- gsock.cpp | 32 +++++++++++++++++++++----------- gsock.h | 4 ++++ 2 files changed, 25 insertions(+), 11 deletions(-) diff --git a/gsock.cpp b/gsock.cpp index 45c87c4..febb47a 100644 --- a/gsock.cpp +++ b/gsock.cpp @@ -257,26 +257,36 @@ int sock::setrecvtime(int Second) } //forgive me, but writing code in hospital is really not a good experience. -int sock::getlocal(std::string& IPStr,int& Port) +typedef int (*_sock_getname_callback_t)(int,sockaddr*,socklen_t*); + +static int _sock_getname_call(int sfd,std::string& ip,int& port,_sock_getname_callback_t fn) { struct sockaddr_in saddr; socklen_t saddrlen=sizeof(saddr); memset(&saddr,0,saddrlen); - int ret=getsockname(_pp->sfd,(sockaddr*)&saddr,&saddrlen); - IPStr=inet_ntoa(saddr.sin_addr); - Port=ntohs(saddr.sin_port); + int ret=fn(sfd,(sockaddr*)&saddr,&saddrlen); + if(ret<0) return ret; //don't bother errno. stop here. + ip=inet_ntoa(saddr.sin_addr); + port=ntohs(saddr.sin_port); return ret; } +int sock::getlocal(std::string& IPStr,int& Port) +{ + if(!(_pp->created)) + { + return -2; + } + return _sock_getname_call(_pp->sfd,IPStr,Port,getsockname); +} + int sock::getpeer(std::string& IPStr,int& Port) { - struct sockaddr_in saddr; - socklen_t saddrlen=sizeof(saddr); - memset(&saddr,0,saddrlen); - int ret=getpeername(_pp->sfd,(sockaddr*)&saddr,&saddrlen); - IPStr=inet_ntoa(saddr.sin_addr); - Port=ntohs(saddr.sin_port); - return ret; + if(!(_pp->created)) + { + return -2; + } + return _sock_getname_call(_pp->sfd,IPStr,Port,getpeername); } struct serversock::_impl diff --git a/gsock.h b/gsock.h index 49184a3..53709d2 100644 --- a/gsock.h +++ b/gsock.h @@ -43,6 +43,10 @@ public: int setsendtime(int Second); int setrecvtime(int Second); + /// Return: + /// 0: Success. No Error. + /// -1: getlocalname() or getpeername() call error. See errno. + /// -2: Socket not created. int getlocal(std::string& IPStr,int& Port); int getpeer(std::string& IPStr,int& Port);