88
99#include < muduo/net/InetAddress.h>
1010
11+ #include < muduo/base/Logging.h>
1112#include < muduo/net/Endian.h>
1213#include < muduo/net/SocketsOps.h>
1314
15+ #include < netdb.h>
1416#include < strings.h> // bzero
1517#include < netinet/in.h>
1618
1921// INADDR_ANY use (type)value casting.
2022#pragma GCC diagnostic ignored "-Wold-style-cast"
2123static const in_addr_t kInaddrAny = INADDR_ANY ;
24+ static const in_addr_t kInaddrLoopback = INADDR_LOOPBACK ;
2225#pragma GCC diagnostic error "-Wold-style-cast"
2326
2427// /* Structure describing an Internet socket address. */
@@ -39,11 +42,12 @@ using namespace muduo::net;
3942
4043BOOST_STATIC_ASSERT (sizeof (InetAddress) == sizeof (struct sockaddr_in ));
4144
42- InetAddress::InetAddress (uint16_t port)
45+ InetAddress::InetAddress (uint16_t port, bool lookbackOnly )
4346{
4447 bzero (&addr_, sizeof addr_);
4548 addr_.sin_family = AF_INET ;
46- addr_.sin_addr .s_addr = sockets::hostToNetwork32 (kInaddrAny );
49+ in_addr_t ip = lookbackOnly ? kInaddrLoopback : kInaddrAny ;
50+ addr_.sin_addr .s_addr = sockets::hostToNetwork32 (ip);
4751 addr_.sin_port = sockets::hostToNetwork16 (port);
4852}
4953
@@ -67,3 +71,29 @@ string InetAddress::toIp() const
6771 return buf;
6872}
6973
74+ static __thread char t_resolveBuffer[64 * 1024 ];
75+
76+ bool InetAddress::resolve (const char * hostname, InetAddress* out)
77+ {
78+ assert (out != NULL );
79+ struct hostent hent;
80+ struct hostent * he = NULL ;
81+ int herrno = 0 ;
82+ bzero (&hent, sizeof (hent));
83+
84+ int ret = gethostbyname_r (hostname, &hent, t_resolveBuffer, sizeof t_resolveBuffer, &he, &herrno);
85+ if (ret == 0 && he != NULL )
86+ {
87+ assert (he->h_addrtype == AF_INET && he->h_length == sizeof (uint32_t ));
88+ out->addr_ .sin_addr = *reinterpret_cast <struct in_addr *>(he->h_addr );
89+ return true ;
90+ }
91+ else
92+ {
93+ if (ret)
94+ {
95+ LOG_SYSERR << " InetAddress::resolve" ;
96+ }
97+ return false ;
98+ }
99+ }
0 commit comments