2 * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 // libs/cutils/socket_loopback_server.c
27 #define LISTEN_BACKLOG 4
29 #define LOOPBACK_DOWN 0
32 #include <sys/socket.h>
33 #include <sys/select.h>
34 #include <sys/types.h>
35 #include <netinet/in.h>
36 #include <sys/ioctl.h>
38 #include <arpa/inet.h>
42 int get_loopback_status(void) {
51 s = socket(AF_INET, SOCK_DGRAM, 0);
58 // query available interfaces
59 ifc.ifc_len = sizeof(buf);
61 if(ioctl(s, SIOCGIFCONF, &ifc) < 0)
63 perror("ioctl(SIOCGIFCONF)");
68 // iterate the list of interfaces
70 ifcnt = ifc.ifc_len / sizeof(struct ifreq);
71 for(i = 0; i < ifcnt; i++)
73 struct sockaddr_in *addr;
74 addr = (struct sockaddr_in *)&ifr->ifr_addr;
76 if (ntohl(addr->sin_addr.s_addr) == INADDR_LOOPBACK)
86 /* open listen() port on loopback interface */
87 int socket_loopback_server(int port, int type)
89 struct sockaddr_in addr;
95 // check the loopback interface has been up in 30 sec
97 if(get_loopback_status() == LOOPBACK_DOWN) {
106 memset(&addr, 0, sizeof(addr));
107 addr.sin_family = AF_INET;
108 addr.sin_port = htons(port);
111 addr.sin_addr.s_addr = htonl(INADDR_ANY);
113 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
115 s = socket(AF_INET, type, 0);
121 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) < 0) {
126 if(bind(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
131 if (type == SOCK_STREAM) {
134 ret = listen(s, LISTEN_BACKLOG);