1 /*
2 * Copyright (c) 2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "napi/native_api.h"
17 #include <cerrno>
18 #include <ifaddrs.h>
19 #include <js_native_api_types.h>
20 #include <net/if.h>
21 #include <sys/inotify.h>
22 #include <utmp.h>
23 #include <uv.h>
24 #include <hilog/log.h>
25
26 #define NO_ERR 0
27 #define SUCCESS 1
28 #define FAIL (-1)
29
30 #undef LOG_DOMAIN
31 #undef LOG_TAG
32 #define LOG_DOMAIN 0xFEFE
33 #define LOG_TAG "MUSL_LIBCTEST"
34
Getifaddrs(napi_env env,napi_callback_info info)35 static napi_value Getifaddrs(napi_env env, napi_callback_info info)
36 {
37 struct ifaddrs *ifc;
38 napi_value result = nullptr;
39 errno = 0;
40 int ret = getifaddrs(&ifc);
41 if (ret != NO_ERR) {
42 OH_LOG_INFO(LOG_APP, "Getifaddrs getifaddrs failed: ret %{public}d errno : %{public}d", ret, errno);
43 napi_create_int32(env, FAIL, &result);
44 return result;
45 }
46 napi_create_int32(env, ret, &result);
47 freeifaddrs(ifc);
48 return result;
49 }
Freeifaddrs(napi_env env,napi_callback_info info)50 static napi_value Freeifaddrs(napi_env env, napi_callback_info info)
51 {
52 napi_value result = nullptr;
53 errno = NO_ERR;
54 struct ifaddrs *ifc;
55 int res = getifaddrs(&ifc);
56 if (res != NO_ERR) {
57 OH_LOG_INFO(LOG_APP, "Freeifaddrs getifaddrs failed: res %{public}d errno : %{public}d", res, errno);
58 napi_create_int32(env, FAIL, &result);
59 return result;
60 }
61 freeifaddrs(ifc);
62 int ret = FAIL;
63 if (errno == NO_ERR) {
64 ret = SUCCESS;
65 }
66 napi_create_int32(env, ret, &result);
67 return result;
68 }
69
70 EXTERN_C_START
Init(napi_env env,napi_value exports)71 static napi_value Init(napi_env env, napi_value exports)
72 {
73 napi_property_descriptor desc[] = {
74 {"getIfAddrs", nullptr, Getifaddrs, nullptr, nullptr, nullptr, napi_default, nullptr},
75 {"freeIfAddrs", nullptr, Freeifaddrs, nullptr, nullptr, nullptr, napi_default, nullptr}};
76 napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
77 return exports;
78 }
79 EXTERN_C_END
80
81 static napi_module demoModule = {
82 .nm_version = 1,
83 .nm_flags = 0,
84 .nm_filename = nullptr,
85 .nm_register_func = Init,
86 .nm_modname = "libifaddrs",
87 .nm_priv = ((void *)0),
88 .reserved = {0},
89 };
90
RegisterModule(void)91 extern "C" __attribute__((constructor)) void RegisterModule(void) { napi_module_register(&demoModule); }
92