5 #include <sys/socket.h>
6 #include <netinet/tcp.h>
8 memcached_return
memcached_connect(memcached_st
*ptr
)
11 struct sockaddr_in localAddr
, servAddr
;
14 LIBMEMCACHED_MEMCACHED_CONNECT_START();
16 if (ptr
->connected
== ptr
->number_of_hosts
)
17 return MEMCACHED_SUCCESS
;
20 return MEMCACHED_NO_SERVERS
;
22 for (x
= 0; x
< ptr
->number_of_hosts
; x
++)
24 if (ptr
->hosts
[x
].fd
== -1)
26 if ((h
= gethostbyname(ptr
->hosts
[x
].hostname
)) == NULL
)
27 return MEMCACHED_HOST_LOCKUP_FAILURE
;
29 servAddr
.sin_family
= h
->h_addrtype
;
30 memcpy((char *) &servAddr
.sin_addr
.s_addr
, h
->h_addr_list
[0], h
->h_length
);
31 servAddr
.sin_port
= htons(ptr
->hosts
[x
].port
);
33 /* Create the socket */
34 if ((ptr
->hosts
[x
].fd
= socket(AF_INET
, SOCK_STREAM
, 0)) < 0)
37 return MEMCACHED_CONNECTION_SOCKET_CREATE_FAILURE
;
41 /* bind any port number */
42 localAddr
.sin_family
= AF_INET
;
43 localAddr
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
44 localAddr
.sin_port
= htons(0);
46 /* For the moment, not getting a nonblocking mode will note be fatal */
47 if (ptr
->flags
& MEM_NO_BLOCK
)
51 flags
= fcntl(ptr
->hosts
[x
].fd
, F_GETFL
, 0);
53 (void)fcntl(ptr
->hosts
[x
].fd
, F_SETFL
, flags
| O_NONBLOCK
);
56 if (ptr
->flags
& MEM_TCP_NODELAY
)
60 setsockopt(ptr
->hosts
[x
].fd
, IPPROTO_TCP
, TCP_NODELAY
,
61 &flag
, (socklen_t
)sizeof(int));
64 /* connect to server */
66 if (connect(ptr
->hosts
[x
].fd
, (struct sockaddr
*) &servAddr
, sizeof(servAddr
)) < 0)
69 /* We are spinning waiting on connect */
73 case EISCONN
: /* We were spinning waiting on connect */
77 return MEMCACHED_HOST_LOCKUP_FAILURE
;
84 LIBMEMCACHED_MEMCACHED_CONNECT_END();
86 return MEMCACHED_SUCCESS
;