revert it due to dlopen error
[sdk/target/sdbd.git] / src / socket_network_client.c
1 /*
2  * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  * Licensed under the Apache License, Version 2.0 (the License);
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an AS IS BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 // libs/cutils/socket_network_client.c
17
18 #include "sockets.h"
19
20 #include <stdlib.h>
21 #include <string.h>
22 #include <unistd.h>
23 #include <errno.h>
24 #include <stddef.h>
25
26 #ifndef HAVE_WINSOCK
27 #include <sys/socket.h>
28 #include <sys/select.h>
29 #include <sys/types.h>
30 #include <netinet/in.h>
31 #include <netdb.h>
32 #endif
33
34
35 /* Connect to port on the IP interface. type is
36  * SOCK_STREAM or SOCK_DGRAM.
37  * return is a file descriptor or -1 on error
38  */
39 int socket_network_client(const char *host, int port, int type)
40 {
41     struct hostent hostbuf, *hp;
42     struct sockaddr_in addr;
43     int s;
44     size_t hstbuflen = 1024;
45     int res, herr;
46     char *tmphstbuf;
47
48     tmphstbuf = malloc(hstbuflen);
49     if (tmphstbuf == NULL) {
50         return -1;
51     }
52
53     while ((res = gethostbyname_r(host, &hostbuf, tmphstbuf, hstbuflen, &hp, &herr)) == ERANGE) {
54         // enlarge the buffer
55         hstbuflen *= 2;
56         void *tmpbuf = realloc(tmphstbuf, hstbuflen);
57         if (tmpbuf == NULL) {
58             if (tmphstbuf != NULL) {
59                 free(tmphstbuf);
60             }
61             return -1;
62         } else {
63             tmphstbuf = tmpbuf;
64         }
65     }
66     if (res || hp == NULL) {
67         if (tmphstbuf != NULL) {
68             free(tmphstbuf);
69         }
70         return -1;
71     }
72     memset(&addr, 0, sizeof(addr));
73     addr.sin_family = hp->h_addrtype;
74     addr.sin_port = htons(port);
75     memcpy(&addr.sin_addr, hp->h_addr, hp->h_length);
76
77     s = socket(hp->h_addrtype, type, 0);
78     if(s < 0) {
79         if (tmphstbuf != NULL) {
80             free(tmphstbuf);
81         }
82         return -1;
83     }
84
85     if(connect(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
86         close(s);
87
88         if (tmphstbuf != NULL) {
89             free(tmphstbuf);
90         }
91         return -1;
92     }
93     if (tmphstbuf != NULL) {
94         free(tmphstbuf);
95     }
96     return s;
97
98 }
99