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