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