Removed all valgrind warning. Thought this error persists and I can not see
[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 *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 if (!new_host_list)
17 return MEMCACHED_MEMORY_ALLOCATION_FAILURE;
18 memset(&new_host_list[ptr->number_of_hosts], 0, sizeof(memcached_host_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)
47 return MEMCACHED_SUCCESS;
48
49 if (!ptr->hosts)
50 {
51 memcached_return rc;
52 rc= memcached_server_add(ptr, NULL, 0);
53
54 if (rc != MEMCACHED_SUCCESS)
55 return rc;
56 }
57
58
59 for (x= 0; x < ptr->number_of_hosts; x++)
60 {
61 if ((h= gethostbyname(ptr->hosts[x].hostname)) == NULL)
62 return MEMCACHED_HOST_LOCKUP_FAILURE;
63
64 servAddr.sin_family= h->h_addrtype;
65 memcpy((char *) &servAddr.sin_addr.s_addr, h->h_addr_list[0], h->h_length);
66 servAddr.sin_port = htons(ptr->hosts[x].port);
67
68 /* Create the socket */
69 if ((ptr->hosts[0].fd= socket(AF_INET, SOCK_STREAM, 0)) < 0)
70 return MEMCACHED_CONNECTION_SOCKET_CREATE_FAILURE;
71
72
73 /* bind any port number */
74 localAddr.sin_family = AF_INET;
75 localAddr.sin_addr.s_addr = htonl(INADDR_ANY);
76 localAddr.sin_port = htons(0);
77
78 if (bind(ptr->hosts[0].fd, (struct sockaddr *) &localAddr, sizeof(localAddr)) < 0)
79 return(MEMCACHED_CONNECTION_BIND_FAILURE);
80
81 /* connect to server */
82 if (connect(ptr->hosts[0].fd, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0)
83 return MEMCACHED_HOST_LOCKUP_FAILURE;
84 }
85
86 ptr->connected= 1;
87
88 return MEMCACHED_SUCCESS;
89 }