根据sockfd获取TCP连接本地地址以及对端地址
摘抄自muduo代码实现。
获取本地地址(LocalAddr):
1 struct sockaddr_in6 sockets::getLocalAddr(int sockfd) 2 { 3 struct sockaddr_in6 localaddr; 4 bzero(&localaddr, sizeof localaddr); 5 auto addrlen = static_cast<socklen_t>(sizeof localaddr); 6 if (::getsockname(sockfd, sockaddr_cast(&localaddr), &addrlen) < 0) 7 { 8 LOG_SYSERR << "sockets::getLocalAddr"; 9 } 10 return localaddr; 11 }
获取对端地址(PeerAddr):
1 struct sockaddr_in6 sockets::getPeerAddr(int sockfd) 2 { 3 struct sockaddr_in6 peeraddr; 4 bzero(&peeraddr, sizeof peeraddr); 5 auto addrlen = static_cast<socklen_t>(sizeof peeraddr); 6 if (::getpeername(sockfd, sockaddr_cast(&peeraddr), &addrlen) < 0) 7 { 8 LOG_SYSERR << "sockets::getPeerAddr"; 9 } 10 return peeraddr; 11 }
PS:
如果您觉得我的文章对您有帮助,可以扫码领取下红包,谢谢!