From 9996b38c19e3565748340e86f9bcc8ae15421386 Mon Sep 17 00:00:00 2001 From: Kiritow-Tablet <1362050620@qq.com> Date: Fri, 4 May 2018 17:44:39 +0800 Subject: [PATCH] Add getlocal,getpeer to class sock --- gsock.cpp | 22 +++++++++++++++++++++- gsock.h | 5 ++++- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/gsock.cpp b/gsock.cpp index 824e045..45c87c4 100644 --- a/gsock.cpp +++ b/gsock.cpp @@ -256,8 +256,28 @@ int sock::setrecvtime(int Second) return setsockopt(sfd,SOL_SOCKET,SO_RCVTIMEO,(const char*)&outtime,sizeof(outtime)); } +//forgive me, but writing code in hospital is really not a good experience. +int sock::getlocal(std::string& IPStr,int& Port) +{ + 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); + return ret; +} - +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; +} struct serversock::_impl { diff --git a/gsock.h b/gsock.h index 09f21a3..49184a3 100644 --- a/gsock.h +++ b/gsock.h @@ -42,6 +42,9 @@ public: int setsendtime(int Second); int setrecvtime(int Second); + + int getlocal(std::string& IPStr,int& Port); + int getpeer(std::string& IPStr,int& Port); private: sock(int); @@ -111,4 +114,4 @@ private: /// Net Tools int DNSResolve(const std::string& HostName,std::string& _out_IPStr); -#endif // _gsock_h +#endif // _gsock_h \ No newline at end of file