Broke library up into multiple files.
[m6w6/libmemcached] / lib / memcached_connect.c
1 #include <memcached.h>
2
3 memcached_return memcached_connect(memcached_st *ptr)
4 {
5 int rc;
6 struct sockaddr_in localAddr, servAddr;
7 struct hostent *h;
8 char *server_name= "localhost";
9
10 if (ptr->connected)
11 return MEMCACHED_SUCCESS;
12
13
14 if ((h= gethostbyname(server_name)) == NULL)
15 {
16 fprintf(stderr, "unknown host '%s'\n", server_name);
17 return MEMCACHED_HOST_LOCKUP_FAILURE;
18 }
19
20 servAddr.sin_family= h->h_addrtype;
21 memcpy((char *) &servAddr.sin_addr.s_addr, h->h_addr_list[0], h->h_length);
22 servAddr.sin_port = htons(MEMCACHED_DEFAULT_PORT);
23
24 /* Create the socket */
25 if ((ptr->fd= socket(AF_INET, SOCK_STREAM, 0)) < 0)
26 {
27 fprintf(stderr, "cannot open socket");
28 return MEMCACHED_CONNECTION_SOCKET_CREATE_FAILURE;
29 }
30
31
32 /* bind any port number */
33 localAddr.sin_family = AF_INET;
34 localAddr.sin_addr.s_addr = htonl(INADDR_ANY);
35 localAddr.sin_port = htons(0);
36
37 if (bind(ptr->fd, (struct sockaddr *) &localAddr, sizeof(localAddr)) < 0)
38 {
39 fprintf(stderr, "cannot bind port TCP %u\n", MEMCACHED_DEFAULT_PORT);
40 return(MEMCACHED_CONNECTION_BIND_FAILURE);
41 }
42
43 /* connect to server */
44 if (connect(ptr->fd, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0)
45 {
46 fprintf(stderr, "cannot connect to host '%s'\n", server_name);
47 return MEMCACHED_HOST_LOCKUP_FAILURE;
48 }
49
50 ptr->connected= 1;
51
52 return MEMCACHED_SUCCESS;
53 }