5b024749b1f58038f24c515361c5d7f49a0e1365
[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 {
35 ptr->my_errno= errno;
36 return MEMCACHED_CONNECTION_SOCKET_CREATE_FAILURE;
37 }
38
39
40 /* bind any port number */
41 localAddr.sin_family = AF_INET;
42 localAddr.sin_addr.s_addr = htonl(INADDR_ANY);
43 localAddr.sin_port = htons(0);
44
45 /* For the moment, not getting a nonblocking mode will note be fatal */
46 if (ptr->flags & MEM_NO_BLOCK)
47 {
48 flags= fcntl(ptr->hosts[0].fd, F_GETFL, 0);
49 if (flags != -1)
50 (void)fcntl(ptr->hosts[0].fd, F_SETFL, flags | O_NONBLOCK);
51 }
52
53 /* connect to server */
54 test_connect:
55 if (connect(ptr->hosts[0].fd, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0)
56 {
57 switch (errno) {
58 /* We are spinning waiting on connect */
59 case EINPROGRESS:
60 case EINTR:
61 goto test_connect;
62 case EISCONN: /* We were spinning waiting on connect */
63 break;
64 default:
65 ptr->my_errno= errno;
66 return MEMCACHED_HOST_LOCKUP_FAILURE;
67 }
68
69 ptr->connected++;
70 }
71 }
72 }
73 LIBMEMCACHED_MEMCACHED_CONNECT_END();
74
75 return MEMCACHED_SUCCESS;
76 }