5 #include <sys/socket.h>
6 #include <netinet/tcp.h>
9 memcached_return
memcached_real_connect(memcached_st
*ptr
, unsigned int server_key
)
11 struct sockaddr_in localAddr
, servAddr
;
14 if (ptr
->hosts
[server_key
].fd
== -1)
16 /* Old connection junk still is in the structure */
17 assert(ptr
->hosts
[server_key
].stack_responses
== 0);
19 if ((h
= gethostbyname(ptr
->hosts
[server_key
].hostname
)) == NULL
)
21 ptr
->my_errno
= h_errno
;
22 return MEMCACHED_HOST_LOCKUP_FAILURE
;
25 servAddr
.sin_family
= h
->h_addrtype
;
26 memcpy((char *) &servAddr
.sin_addr
.s_addr
, h
->h_addr_list
[0], h
->h_length
);
27 servAddr
.sin_port
= htons(ptr
->hosts
[server_key
].port
);
29 /* Create the socket */
30 if ((ptr
->hosts
[server_key
].fd
= socket(AF_INET
, SOCK_STREAM
, 0)) < 0)
33 return MEMCACHED_CONNECTION_SOCKET_CREATE_FAILURE
;
37 /* bind any port number */
38 localAddr
.sin_family
= AF_INET
;
39 localAddr
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
40 localAddr
.sin_port
= htons(0);
42 /* For the moment, not getting a nonblocking mode will note be fatal */
43 if (ptr
->flags
& MEM_NO_BLOCK
)
47 flags
= fcntl(ptr
->hosts
[server_key
].fd
, F_GETFL
, 0);
49 (void)fcntl(ptr
->hosts
[server_key
].fd
, F_SETFL
, flags
| O_NONBLOCK
);
52 if (ptr
->flags
& MEM_TCP_NODELAY
)
56 setsockopt(ptr
->hosts
[server_key
].fd
, IPPROTO_TCP
, TCP_NODELAY
,
57 &flag
, (socklen_t
)sizeof(int));
60 /* connect to server */
62 if (connect(ptr
->hosts
[server_key
].fd
, (struct sockaddr
*) &servAddr
, sizeof(servAddr
)) < 0)
65 /* We are spinning waiting on connect */
70 case EISCONN
: /* We were spinning waiting on connect */
74 return MEMCACHED_ERRNO
;
78 assert(ptr
->hosts
[server_key
].stack_responses
== 0);
81 return MEMCACHED_SUCCESS
;
85 memcached_return
memcached_connect(memcached_st
*ptr
, unsigned int server_key
)
88 LIBMEMCACHED_MEMCACHED_CONNECT_START();
90 if (ptr
->connected
== ptr
->number_of_hosts
)
91 return MEMCACHED_SUCCESS
;
94 return MEMCACHED_NO_SERVERS
;
96 /* We need to clean up the multi startup piece */
98 rc
= memcached_real_connect(ptr
, server_key
);
103 for (x
= 0; x
< ptr
->number_of_hosts
; x
++)
104 rc
= memcached_real_connect(ptr
, x
);
106 LIBMEMCACHED_MEMCACHED_CONNECT_END();