memcached_server_add() now works so you can connect to host other then
[m6w6/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 *host_ptr, *prev_ptr;
6
7 if (!port)
8 port= MEMCACHED_DEFAULT_PORT;
9
10 if (!hostname)
11 hostname= "localhost";
12
13 if (ptr->hosts)
14 {
15 for (host_ptr= ptr->hosts; host_ptr; host_ptr= host_ptr->next)
16 prev_ptr= host_ptr;
17 host_ptr= (memcached_host_st *)malloc(sizeof(memcached_host_st));
18 if (!host_ptr)
19 return MEMCACHED_MEMORY_ALLOCATION_FAILURE;
20 prev_ptr->next= host_ptr;
21 }
22 else
23 {
24 ptr->hosts=
25 host_ptr= (memcached_host_st *)malloc(sizeof(memcached_host_st));
26 if (!host_ptr)
27 return MEMCACHED_MEMORY_ALLOCATION_FAILURE;
28 }
29
30 memset(host_ptr, 0, sizeof(memcached_host_st));
31 host_ptr->hostname= (char *)malloc(sizeof(char) * strlen(hostname));
32
33 if (!host_ptr->hostname)
34 {
35 free(host_ptr);
36 return MEMCACHED_MEMORY_ALLOCATION_FAILURE;
37 }
38 memcpy(host_ptr->hostname, hostname, strlen(hostname));
39 host_ptr->port= port;
40
41 return MEMCACHED_SUCCESS;
42 }
43
44 memcached_return memcached_connect(memcached_st *ptr)
45 {
46 struct sockaddr_in localAddr, servAddr;
47 struct hostent *h;
48 memcached_host_st *host_ptr;
49
50 if (ptr->connected)
51 return MEMCACHED_SUCCESS;
52
53 if (!ptr->hosts)
54 {
55 memcached_return rc;
56 rc= memcached_server_add(ptr, NULL, 0);
57
58 if (rc != MEMCACHED_SUCCESS)
59 return rc;
60 }
61
62
63 for (host_ptr= ptr->hosts; host_ptr; host_ptr= host_ptr->next)
64 {
65 if ((h= gethostbyname(host_ptr->hostname)) == NULL)
66 {
67 fprintf(stderr, "unknown host '%s'\n", host_ptr->hostname);
68 return MEMCACHED_HOST_LOCKUP_FAILURE;
69 }
70
71 servAddr.sin_family= h->h_addrtype;
72 memcpy((char *) &servAddr.sin_addr.s_addr, h->h_addr_list[0], h->h_length);
73 servAddr.sin_port = htons(host_ptr->port);
74
75 /* Create the socket */
76 if ((ptr->fd= socket(AF_INET, SOCK_STREAM, 0)) < 0)
77 {
78 fprintf(stderr, "cannot open socket");
79 return MEMCACHED_CONNECTION_SOCKET_CREATE_FAILURE;
80 }
81
82
83 /* bind any port number */
84 localAddr.sin_family = AF_INET;
85 localAddr.sin_addr.s_addr = htonl(INADDR_ANY);
86 localAddr.sin_port = htons(0);
87
88 if (bind(ptr->fd, (struct sockaddr *) &localAddr, sizeof(localAddr)) < 0)
89 {
90 fprintf(stderr, "cannot bind port TCP %u\n", host_ptr->port);
91 return(MEMCACHED_CONNECTION_BIND_FAILURE);
92 }
93
94 /* connect to server */
95 if (connect(ptr->fd, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0)
96 {
97 fprintf(stderr, "cannot connect to host '%s' (%u) (error: %s)\n", host_ptr->hostname,
98 host_ptr->port,
99 strerror(errno));
100 return MEMCACHED_HOST_LOCKUP_FAILURE;
101 }
102 }
103
104 ptr->connected= 1;
105
106 return MEMCACHED_SUCCESS;
107 }