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 if ((h
= gethostbyname(ptr
->hosts
[server_key
].hostname
)) == NULL
)
18 ptr
->my_errno
= h_errno
;
19 return MEMCACHED_HOST_LOCKUP_FAILURE
;
22 servAddr
.sin_family
= h
->h_addrtype
;
23 memcpy((char *) &servAddr
.sin_addr
.s_addr
, h
->h_addr_list
[0], h
->h_length
);
24 servAddr
.sin_port
= htons(ptr
->hosts
[server_key
].port
);
26 /* Create the socket */
27 if ((ptr
->hosts
[server_key
].fd
= socket(AF_INET
, SOCK_STREAM
, 0)) < 0)
30 return MEMCACHED_CONNECTION_SOCKET_CREATE_FAILURE
;
34 /* bind any port number */
35 localAddr
.sin_family
= AF_INET
;
36 localAddr
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
37 localAddr
.sin_port
= htons(0);
39 /* For the moment, not getting a nonblocking mode will note be fatal */
40 if (ptr
->flags
& MEM_NO_BLOCK
)
44 flags
= fcntl(ptr
->hosts
[server_key
].fd
, F_GETFL
, 0);
46 (void)fcntl(ptr
->hosts
[server_key
].fd
, F_SETFL
, flags
| O_NONBLOCK
);
49 if (ptr
->flags
& MEM_TCP_NODELAY
)
53 setsockopt(ptr
->hosts
[server_key
].fd
, IPPROTO_TCP
, TCP_NODELAY
,
54 &flag
, (socklen_t
)sizeof(int));
57 /* connect to server */
59 if (connect(ptr
->hosts
[server_key
].fd
, (struct sockaddr
*) &servAddr
, sizeof(servAddr
)) < 0)
62 /* We are spinning waiting on connect */
67 case EISCONN
: /* We were spinning waiting on connect */
71 return MEMCACHED_ERRNO
;
77 return MEMCACHED_SUCCESS
;
81 memcached_return
memcached_connect(memcached_st
*ptr
, unsigned int server_key
)
84 LIBMEMCACHED_MEMCACHED_CONNECT_START();
86 if (ptr
->connected
== ptr
->number_of_hosts
)
87 return MEMCACHED_SUCCESS
;
90 return MEMCACHED_NO_SERVERS
;
92 /* We need to clean up the multi startup piece */
94 rc
= memcached_real_connect(ptr
, server_key
);
99 for (x
= 0; x
< ptr
->number_of_hosts
; x
++)
100 rc
= memcached_real_connect(ptr
, x
);
102 LIBMEMCACHED_MEMCACHED_CONNECT_END();