Skip to content

Commit 20690cd

Browse files
committed
set_hostinfo
1 parent 4966c12 commit 20690cd

File tree

1 file changed

+20
-26
lines changed

1 file changed

+20
-26
lines changed

src/libmemcached/connect.cc

Lines changed: 20 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -18,50 +18,44 @@
1818

1919
#include <cassert>
2020

21-
2221
static memcached_return_t set_hostinfo(memcached_instance_st *server) {
2322
assert(server->type != MEMCACHED_CONNECTION_UNIX_SOCKET);
23+
assert(server->hostname());
24+
2425
server->clear_addrinfo();
2526

26-
char str_port[MEMCACHED_NI_MAXSERV] = {0};
27+
char str_host[MEMCACHED_NI_MAXHOST] = {0}, str_port[MEMCACHED_NI_MAXSERV] = {0};
2728
errno = 0;
28-
int length = snprintf(str_port, MEMCACHED_NI_MAXSERV, "%u", uint32_t(server->port()));
29-
if (length >= MEMCACHED_NI_MAXSERV or length <= 0 or errno) {
29+
30+
auto length = snprintf(str_port, MEMCACHED_NI_MAXSERV, "%u", uint32_t(server->port()));
31+
if (length <= 0 or errno) {
3032
return memcached_set_error(*server, MEMCACHED_MEMORY_ALLOCATION_FAILURE, MEMCACHED_AT,
3133
memcached_literal_param("snprintf(NI_MAXSERV)"));
3234
}
3335

34-
struct addrinfo hints;
35-
memset(&hints, 0, sizeof(struct addrinfo));
36-
36+
struct addrinfo hints{};
3737
hints.ai_family = AF_UNSPEC;
3838
if (memcached_is_udp(server->root)) {
3939
hints.ai_protocol = IPPROTO_UDP;
4040
hints.ai_socktype = SOCK_DGRAM;
4141
} else {
42-
hints.ai_socktype = SOCK_STREAM;
4342
hints.ai_protocol = IPPROTO_TCP;
43+
hints.ai_socktype = SOCK_STREAM;
4444
}
4545

46-
assert(server->address_info == NULL);
47-
assert(server->address_info_next == NULL);
48-
int errcode;
49-
char hostname[MEMCACHED_NI_MAXHOST];
50-
const char *addr;
51-
char *p;
52-
53-
assert(server->hostname());
54-
// drop [] from address, commonly used for IPv6
55-
addr = server->hostname();
56-
if (*addr == '[') {
57-
strcpy(hostname, addr +1);
58-
p = strchr(hostname, ']');
59-
if (p) {
60-
*p = 0;
61-
addr = hostname;
62-
}
46+
auto hostname = server->hostname();
47+
if (*hostname == '[') {
48+
auto closing_bracket = &hostname[strlen(hostname) - 1];
49+
if (*closing_bracket == ']') {
50+
auto host_len = closing_bracket - hostname - 1;
51+
if (host_len < MEMCACHED_NI_MAXHOST) {
52+
hostname = strncpy(str_host, hostname + 1, host_len);
53+
}
54+
}
6355
}
64-
switch (errcode = getaddrinfo(addr, str_port, &hints, &server->address_info)) {
56+
57+
auto errcode = getaddrinfo(hostname, str_port, &hints, &server->address_info);
58+
switch (errcode) {
6559
case 0:
6660
server->address_info_next = server->address_info;
6761
server->state = MEMCACHED_SERVER_STATE_ADDRINFO;

0 commit comments

Comments
 (0)