d0658f33e57d2e92c267b8442154d49cba06e7a2
[awesomized/libmemcached] / lib / memcached_connect.c
1 #include <memcached.h>
2
3 memcached_return memcached_server_add(memcached_st *ptr, char *hostname, unsigned int port)
4 {
5 memcached_host_st *new_host_list;
6 char *new_hostname;
7
8 if (!port)
9 port= MEMCACHED_DEFAULT_PORT;
10
11 if (!hostname)
12 hostname= "localhost";
13
14
15 new_host_list= (memcached_host_st *)realloc(ptr->hosts, sizeof(memcached_host_st) * (ptr->number_of_hosts+1));
16 memset((new_host_list + (sizeof(memcached_host_st) * ptr->number_of_hosts)) - sizeof(memcached_host_st),
17 0, sizeof(memcached_host_st));
18
19 if (!new_host_list)
20 return MEMCACHED_MEMORY_ALLOCATION_FAILURE;
21
22 ptr->hosts= new_host_list;
23
24 new_hostname=
25 (char *)malloc(sizeof(char) * (strlen(hostname)+1));
26 if (!new_hostname)
27 return MEMCACHED_MEMORY_ALLOCATION_FAILURE;
28
29 memset(new_hostname, 0, strlen(hostname)+1);
30 memcpy(new_hostname, hostname, strlen(hostname));
31 ptr->hosts[ptr->number_of_hosts].hostname= new_hostname;
32 ptr->hosts[ptr->number_of_hosts].port= port;
33 ptr->hosts[ptr->number_of_hosts].fd= -1;
34 ptr->number_of_hosts++;
35
36 return MEMCACHED_SUCCESS;
37 }
38
39 memcached_return memcached_connect(memcached_st *ptr)
40 {
41 unsigned int x;
42 struct sockaddr_in localAddr, servAddr;
43 struct hostent *h;
44
45 if (ptr->connected)
46 return MEMCACHED_SUCCESS;
47
48 if (!ptr->hosts)
49 {
50 memcached_return rc;
51 rc= memcached_server_add(ptr, NULL, 0);
52
53 if (rc != MEMCACHED_SUCCESS)
54 return rc;
55 }
56
57
58 for (x= 0; x < ptr->number_of_hosts; x++)
59 {
60 if ((h= gethostbyname(ptr->hosts[x].hostname)) == NULL)
61 return MEMCACHED_HOST_LOCKUP_FAILURE;
62
63 servAddr.sin_family= h->h_addrtype;
64 memcpy((char *) &servAddr.sin_addr.s_addr, h->h_addr_list[0], h->h_length);
65 servAddr.sin_port = htons(ptr->hosts[x].port);
66
67 /* Create the socket */
68 if ((ptr->hosts[0].fd= socket(AF_INET, SOCK_STREAM, 0)) < 0)
69 return MEMCACHED_CONNECTION_SOCKET_CREATE_FAILURE;
70
71
72 /* bind any port number */
73 localAddr.sin_family = AF_INET;
74 localAddr.sin_addr.s_addr = htonl(INADDR_ANY);
75 localAddr.sin_port = htons(0);
76
77 if (bind(ptr->hosts[0].fd, (struct sockaddr *) &localAddr, sizeof(localAddr)) < 0)
78 return(MEMCACHED_CONNECTION_BIND_FAILURE);
79
80 /* connect to server */
81 if (connect(ptr->hosts[0].fd, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0)
82 return MEMCACHED_HOST_LOCKUP_FAILURE;
83 }
84
85 ptr->connected= 1;
86
87 return MEMCACHED_SUCCESS;
88 }