Merge Mark's test code.
[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 if (!port)
6 port= MEMCACHED_DEFAULT_PORT;
7
8 if (!hostname)
9 hostname= "localhost";
10
11
12 ptr->hosts= (memcached_host_st *)realloc(ptr->hosts, sizeof(memcached_host_st) * (ptr->number_of_hosts+1));
13 ptr->hosts[ptr->number_of_hosts].hostname=
14 (char *)malloc(sizeof(char) * (strlen(hostname)+1));
15 memset(ptr->hosts[ptr->number_of_hosts].hostname, 0, strlen(hostname)+1);
16 memcpy(ptr->hosts[ptr->number_of_hosts].hostname, hostname, strlen(hostname));
17 ptr->hosts[ptr->number_of_hosts].port= port;
18 ptr->hosts[ptr->number_of_hosts].fd= -1;
19 ptr->number_of_hosts++;
20
21 return MEMCACHED_SUCCESS;
22 }
23
24 memcached_return memcached_connect(memcached_st *ptr)
25 {
26 unsigned int x;
27 struct sockaddr_in localAddr, servAddr;
28 struct hostent *h;
29
30 if (ptr->connected)
31 return MEMCACHED_SUCCESS;
32
33 if (!ptr->hosts)
34 {
35 memcached_return rc;
36 rc= memcached_server_add(ptr, NULL, 0);
37
38 if (rc != MEMCACHED_SUCCESS)
39 return rc;
40 }
41
42
43 for (x= 0; x < ptr->number_of_hosts; x++)
44 {
45 if ((h= gethostbyname(ptr->hosts[x].hostname)) == NULL)
46 return MEMCACHED_HOST_LOCKUP_FAILURE;
47
48 servAddr.sin_family= h->h_addrtype;
49 memcpy((char *) &servAddr.sin_addr.s_addr, h->h_addr_list[0], h->h_length);
50 servAddr.sin_port = htons(ptr->hosts[x].port);
51
52 /* Create the socket */
53 if ((ptr->hosts[0].fd= socket(AF_INET, SOCK_STREAM, 0)) < 0)
54 return MEMCACHED_CONNECTION_SOCKET_CREATE_FAILURE;
55
56
57 /* bind any port number */
58 localAddr.sin_family = AF_INET;
59 localAddr.sin_addr.s_addr = htonl(INADDR_ANY);
60 localAddr.sin_port = htons(0);
61
62 if (bind(ptr->hosts[0].fd, (struct sockaddr *) &localAddr, sizeof(localAddr)) < 0)
63 return(MEMCACHED_CONNECTION_BIND_FAILURE);
64
65 /* connect to server */
66 if (connect(ptr->hosts[0].fd, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0)
67 return MEMCACHED_HOST_LOCKUP_FAILURE;
68 }
69
70 ptr->connected= 1;
71
72 return MEMCACHED_SUCCESS;
73 }