5 #include <sys/socket.h>
6 #include <netinet/tcp.h>
8 memcached_return
memcached_real_connect(memcached_st
*ptr
, unsigned int server_key
)
10 struct sockaddr_in localAddr
, servAddr
;
13 if (ptr
->hosts
[server_key
].fd
== -1)
15 if ((h
= gethostbyname(ptr
->hosts
[server_key
].hostname
)) == NULL
)
16 return MEMCACHED_HOST_LOCKUP_FAILURE
;
18 servAddr
.sin_family
= h
->h_addrtype
;
19 memcpy((char *) &servAddr
.sin_addr
.s_addr
, h
->h_addr_list
[0], h
->h_length
);
20 servAddr
.sin_port
= htons(ptr
->hosts
[server_key
].port
);
22 /* Create the socket */
23 if ((ptr
->hosts
[server_key
].fd
= socket(AF_INET
, SOCK_STREAM
, 0)) < 0)
26 return MEMCACHED_CONNECTION_SOCKET_CREATE_FAILURE
;
30 /* bind any port number */
31 localAddr
.sin_family
= AF_INET
;
32 localAddr
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
33 localAddr
.sin_port
= htons(0);
35 /* For the moment, not getting a nonblocking mode will note be fatal */
36 if (ptr
->flags
& MEM_NO_BLOCK
)
40 flags
= fcntl(ptr
->hosts
[server_key
].fd
, F_GETFL
, 0);
42 (void)fcntl(ptr
->hosts
[server_key
].fd
, F_SETFL
, flags
| O_NONBLOCK
);
45 if (ptr
->flags
& MEM_TCP_NODELAY
)
49 setsockopt(ptr
->hosts
[server_key
].fd
, IPPROTO_TCP
, TCP_NODELAY
,
50 &flag
, (socklen_t
)sizeof(int));
53 /* connect to server */
55 if (connect(ptr
->hosts
[server_key
].fd
, (struct sockaddr
*) &servAddr
, sizeof(servAddr
)) < 0)
58 /* We are spinning waiting on connect */
62 case EISCONN
: /* We were spinning waiting on connect */
66 return MEMCACHED_HOST_LOCKUP_FAILURE
;
72 return MEMCACHED_SUCCESS
;
76 memcached_return
memcached_connect(memcached_st
*ptr
, unsigned int server_key
)
79 LIBMEMCACHED_MEMCACHED_CONNECT_START();
81 if (ptr
->connected
== ptr
->number_of_hosts
)
82 return MEMCACHED_SUCCESS
;
85 return MEMCACHED_NO_SERVERS
;
87 /* We need to clean up the multi startup piece */
89 rc
= memcached_real_connect(ptr
, server_key
);
94 for (x
= 0; x
< ptr
->number_of_hosts
; x
++)
95 rc
= memcached_real_connect(ptr
, x
);
97 LIBMEMCACHED_MEMCACHED_CONNECT_END();