Increment and decrement now works.
[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) * (size_t)ptr->number_of_hosts);
13 ptr->hosts[ptr->number_of_hosts].hostname=
14 (char *)malloc(sizeof(char) * strlen(hostname));
15 memcpy(ptr->hosts[ptr->number_of_hosts].hostname, hostname, strlen(hostname));
16 ptr->hosts[ptr->number_of_hosts].port= port;
17 ptr->hosts[ptr->number_of_hosts].fd= -1;
18 ptr->number_of_hosts++;
19
20 return MEMCACHED_SUCCESS;
21 }
22
23 memcached_return memcached_connect(memcached_st *ptr)
24 {
25 unsigned int x;
26 struct sockaddr_in localAddr, servAddr;
27 struct hostent *h;
28 memcached_host_st *host_ptr;
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 {
47 fprintf(stderr, "unknown host '%s'\n", ptr->hosts[x].hostname);
48 return MEMCACHED_HOST_LOCKUP_FAILURE;
49 }
50
51 servAddr.sin_family= h->h_addrtype;
52 memcpy((char *) &servAddr.sin_addr.s_addr, h->h_addr_list[0], h->h_length);
53 servAddr.sin_port = htons(ptr->hosts[x].port);
54
55 /* Create the socket */
56 if ((ptr->hosts[0].fd= socket(AF_INET, SOCK_STREAM, 0)) < 0)
57 {
58 fprintf(stderr, "cannot open socket");
59 return MEMCACHED_CONNECTION_SOCKET_CREATE_FAILURE;
60 }
61
62
63 /* bind any port number */
64 localAddr.sin_family = AF_INET;
65 localAddr.sin_addr.s_addr = htonl(INADDR_ANY);
66 localAddr.sin_port = htons(0);
67
68 if (bind(ptr->hosts[0].fd, (struct sockaddr *) &localAddr, sizeof(localAddr)) < 0)
69 {
70 fprintf(stderr, "cannot bind port TCP %u\n", ptr->hosts[x].port);
71 return(MEMCACHED_CONNECTION_BIND_FAILURE);
72 }
73
74 /* connect to server */
75 if (connect(ptr->hosts[0].fd, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0)
76 {
77 fprintf(stderr, "cannot connect to host '%s' (%u) (error: %s)\n", ptr->hosts[x].hostname,
78 ptr->hosts[x].port,
79 strerror(errno));
80 return MEMCACHED_HOST_LOCKUP_FAILURE;
81 }
82 }
83
84 ptr->connected= 1;
85
86 return MEMCACHED_SUCCESS;
87 }