2120db5c7b4e3d3a5f5aa8bde378490bbf6c765f
[awesomized/libmemcached] / lib / memcached_connect.c
1 #include "common.h"
2
3 #include <fcntl.h>
4
5 memcached_return memcached_connect(memcached_st *ptr)
6 {
7 unsigned int x;
8 struct sockaddr_in localAddr, servAddr;
9 struct hostent *h;
10
11 LIBMEMCACHED_MEMCACHED_CONNECT_START();
12
13 if (ptr->connected == ptr->number_of_hosts)
14 return MEMCACHED_SUCCESS;
15
16 if (!ptr->hosts)
17 return MEMCACHED_NO_SERVERS;
18
19 for (x= 0; x < ptr->number_of_hosts; x++)
20 {
21 if (ptr->hosts[x].fd == -1)
22 {
23 int flags;
24
25 if ((h= gethostbyname(ptr->hosts[x].hostname)) == NULL)
26 return MEMCACHED_HOST_LOCKUP_FAILURE;
27
28 servAddr.sin_family= h->h_addrtype;
29 memcpy((char *) &servAddr.sin_addr.s_addr, h->h_addr_list[0], h->h_length);
30 servAddr.sin_port = htons(ptr->hosts[x].port);
31
32 /* Create the socket */
33 if ((ptr->hosts[0].fd= socket(AF_INET, SOCK_STREAM, 0)) < 0)
34 return MEMCACHED_CONNECTION_SOCKET_CREATE_FAILURE;
35
36
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);
41
42 #ifdef NOT_YET
43 /* For the moment, not getting a nonblocking mode will note be fatal */
44 flags= fcntl(ptr->hosts[0].fd, F_GETFL, 0);
45 if (flags != -1)
46 (void)fcntl(ptr->hosts[0].fd, F_SETFL, flags | O_NONBLOCK);
47 #endif
48
49 /* connect to server */
50 if (connect(ptr->hosts[0].fd, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0)
51 return MEMCACHED_HOST_LOCKUP_FAILURE;
52
53 ptr->connected++;
54 }
55 }
56 LIBMEMCACHED_MEMCACHED_CONNECT_END();
57
58 return MEMCACHED_SUCCESS;
59 }