Fix bug in getlocal(),getpeer().

This commit is contained in:
Kirigaya Kazuto 2018-05-04 18:04:29 +08:00
parent 9996b38c19
commit eb2337ae22
2 changed files with 25 additions and 11 deletions

View File

@ -257,26 +257,36 @@ int sock::setrecvtime(int Second)
} }
//forgive me, but writing code in hospital is really not a good experience. //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; struct sockaddr_in saddr;
socklen_t saddrlen=sizeof(saddr); socklen_t saddrlen=sizeof(saddr);
memset(&saddr,0,saddrlen); memset(&saddr,0,saddrlen);
int ret=getsockname(_pp->sfd,(sockaddr*)&saddr,&saddrlen); int ret=fn(sfd,(sockaddr*)&saddr,&saddrlen);
IPStr=inet_ntoa(saddr.sin_addr); if(ret<0) return ret; //don't bother errno. stop here.
Port=ntohs(saddr.sin_port); ip=inet_ntoa(saddr.sin_addr);
port=ntohs(saddr.sin_port);
return ret; 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) int sock::getpeer(std::string& IPStr,int& Port)
{ {
struct sockaddr_in saddr; if(!(_pp->created))
socklen_t saddrlen=sizeof(saddr); {
memset(&saddr,0,saddrlen); return -2;
int ret=getpeername(_pp->sfd,(sockaddr*)&saddr,&saddrlen); }
IPStr=inet_ntoa(saddr.sin_addr); return _sock_getname_call(_pp->sfd,IPStr,Port,getpeername);
Port=ntohs(saddr.sin_port);
return ret;
} }
struct serversock::_impl struct serversock::_impl

View File

@ -43,6 +43,10 @@ public:
int setsendtime(int Second); int setsendtime(int Second);
int setrecvtime(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 getlocal(std::string& IPStr,int& Port);
int getpeer(std::string& IPStr,int& Port); int getpeer(std::string& IPStr,int& Port);