-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathinet_address.cpp
More file actions
91 lines (77 loc) · 2.31 KB
/
Copy pathinet_address.cpp
File metadata and controls
91 lines (77 loc) · 2.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <strings.h> // bzero
#include <netinet/in.h>
#include <assert.h>
#include <netdb.h>
#include "socket_ops.h"
#include "ydx_endian.h"
#include "inet_address.h"
// INADDR_ANY use (type)value casting.
#pragma GCC diagnostic ignored "-Wold-style-cast"
static const in_addr_t kInaddrAny = INADDR_ANY;
static const in_addr_t kInaddrLoopback = INADDR_LOOPBACK;
#pragma GCC diagnostic error "-Wold-style-cast"
// /* Structure describing an Internet socket address. */
// struct sockaddr_in {
// sa_family_t sin_family; /* address family: AF_INET */
// uint16_t sin_port; /* port in network byte order */
// struct in_addr sin_addr; /* internet address */
// };
// /* Internet address. */
// typedef uint32_t in_addr_t;
// struct in_addr {
// in_addr_t s_addr; /* address in network byte order */
// };
using namespace ydx;
InetAddress::InetAddress(uint16_t port, bool loopbackOnly)
{
bzero(&addr_, sizeof addr_);
addr_.sin_family = AF_INET;
in_addr_t ip = loopbackOnly ? kInaddrLoopback : kInaddrAny;
addr_.sin_addr.s_addr = sockets::hostToNetwork32(ip);
addr_.sin_port = sockets::hostToNetwork16(port);
}
InetAddress::InetAddress(StringArg ip, uint16_t port)
{
bzero(&addr_, sizeof addr_);
sockets::fromIpPort(ip.c_str(), port, &addr_);
}
std::string InetAddress::toIpPort() const
{
char buf[32];
sockets::toIpPort(buf, sizeof buf, addr_);
return std::string(buf);
}
std::string InetAddress::toIp() const
{
char buf[32];
sockets::toIp(buf, sizeof buf, addr_);
return std::string(buf);
}
uint16_t InetAddress::toPort() const
{
return sockets::networkToHost16(addr_.sin_port);
}
static __thread char t_resolveBuffer[64 * 1024];
bool InetAddress::resolve(StringArg hostname, InetAddress* out)
{
assert(out != NULL);
struct hostent hent;
struct hostent* he = NULL;
int herrno = 0;
bzero(&hent, sizeof(hent));
int ret = gethostbyname_r(hostname.c_str(), &hent, t_resolveBuffer, sizeof t_resolveBuffer, &he, &herrno);
if (ret == 0 && he != NULL)
{
assert(he->h_addrtype == AF_INET && he->h_length == sizeof(uint32_t));
out->addr_.sin_addr = *reinterpret_cast<struct in_addr*>(he->h_addr);
return true;
}
else
{
if (ret)
{
printf("resolve inet_address failed..\n");
}
return false;
}
}