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