Adding buffered IO to reads
[awesomized/libmemcached] / lib / memcached_connect.c
1 #include "common.h"
2
3 memcached_return memcached_connect(memcached_st *ptr)
4 {
5 unsigned int x;
6 struct sockaddr_in localAddr, servAddr;
7 struct hostent *h;
8
9 LIBMEMCACHED_MEMCACHED_CONNECT_START();
10
11 if (ptr->connected == ptr->number_of_hosts)
12 return MEMCACHED_SUCCESS;
13
14 if (!ptr->hosts)
15 return MEMCACHED_NO_SERVERS;
16
17 for (x= 0; x < ptr->number_of_hosts; x++)
18 {
19 if (ptr->hosts[x].fd == -1)
20 {
21 if ((h= gethostbyname(ptr->hosts[x].hostname)) == NULL)
22 return MEMCACHED_HOST_LOCKUP_FAILURE;
23
24 servAddr.sin_family= h->h_addrtype;
25 memcpy((char *) &servAddr.sin_addr.s_addr, h->h_addr_list[0], h->h_length);
26 servAddr.sin_port = htons(ptr->hosts[x].port);
27
28 /* Create the socket */
29 if ((ptr->hosts[0].fd= socket(AF_INET, SOCK_STREAM, 0)) < 0)
30 return MEMCACHED_CONNECTION_SOCKET_CREATE_FAILURE;
31
32
33 /* bind any port number */
34 localAddr.sin_family = AF_INET;
35 localAddr.sin_addr.s_addr = htonl(INADDR_ANY);
36 localAddr.sin_port = htons(0);
37
38 if (bind(ptr->hosts[0].fd, (struct sockaddr *) &localAddr, sizeof(localAddr)) < 0)
39 return(MEMCACHED_CONNECTION_BIND_FAILURE);
40
41 /* connect to server */
42 if (connect(ptr->hosts[0].fd, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0)
43 return MEMCACHED_HOST_LOCKUP_FAILURE;
44
45 ptr->connected++;
46 }
47 }
48 LIBMEMCACHED_MEMCACHED_CONNECT_END();
49
50 return MEMCACHED_SUCCESS;
51 }