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
;
36 /* bind any port number */
37 localAddr
.sin_family
= AF_INET
;
38 localAddr
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
39 localAddr
.sin_port
= htons(0);
41 /* For the moment, not getting a nonblocking mode will note be fatal */
42 if (ptr
->flags
& MEM_NO_BLOCK
)
46 flags
= fcntl(ptr
->hosts
[server_key
].fd
, F_GETFL
, 0);
48 (void)fcntl(ptr
->hosts
[server_key
].fd
, F_SETFL
, flags
| O_NONBLOCK
);
51 if (ptr
->flags
& MEM_TCP_NODELAY
)
55 setsockopt(ptr
->hosts
[server_key
].fd
, IPPROTO_TCP
, TCP_NODELAY
,
56 &flag
, (socklen_t
)sizeof(int));
61 setsockopt(ptr
->hosts
[server_key
].fd
, SOL_SOCKET
, SO_SNDBUF
,
62 &ptr
->send_size
, (socklen_t
)sizeof(int));
67 setsockopt(ptr
->hosts
[server_key
].fd
, SOL_SOCKET
, SO_SNDBUF
,
68 &ptr
->recv_size
, (socklen_t
)sizeof(int));
71 /* connect to server */
73 if (connect(ptr
->hosts
[server_key
].fd
, (struct sockaddr
*) &servAddr
, sizeof(servAddr
)) < 0)
76 /* We are spinning waiting on connect */
81 case EISCONN
: /* We were spinning waiting on connect */
85 return MEMCACHED_ERRNO
;
89 assert(ptr
->hosts
[server_key
].stack_responses
== 0);
92 return MEMCACHED_SUCCESS
;
96 memcached_return
memcached_connect(memcached_st
*ptr
, unsigned int server_key
)
98 memcached_return rc
= MEMCACHED_NO_SERVERS
;
99 LIBMEMCACHED_MEMCACHED_CONNECT_START();
101 if (ptr
->connected
== ptr
->number_of_hosts
)
102 return MEMCACHED_SUCCESS
;
105 return MEMCACHED_NO_SERVERS
;
107 /* We need to clean up the multi startup piece */
109 rc
= memcached_real_connect(ptr
, server_key
);
114 for (x
= 0; x
< ptr
->number_of_hosts
; x
++)
116 memcached_return possible_rc
;
118 possible_rc
= memcached_real_connect(ptr
, x
);
119 rc
= MEMCACHED_SUCCESS
;
121 if (possible_rc
!= MEMCACHED_SUCCESS
)
122 rc
= MEMCACHED_SOME_ERRORS
;
125 LIBMEMCACHED_MEMCACHED_CONNECT_END();