1# 管理网络连接(C/C++) 2<!--Kit: Network Kit--> 3<!--Subsystem: Communication--> 4<!--Owner: @wmyao_mm--> 5<!--Designer: @guo-min_net--> 6<!--Tester: @tongxilin--> 7<!--Adviser: @zhang_yixin13--> 8 9## 场景介绍 10 11NetConnection模块提供了常用网络信息查询的能力。 12 13## 接口说明 14 15NetConnection常用接口如下表所示,详细的接口说明请参考[net_connection.h](../reference/apis-network-kit/capi-net-connection-h.md)。 16 17 18| 接口名 | 描述 | 19| -------- | -------- | 20| OH_NetConn_HasDefaultNet(int32_t \*hasDefaultNet) | 检查默认数据网络是否被激活,判断设备是否有网络连接,以便在应用程序中采取相应的措施。 | 21| OH_NetConn_GetDefaultNet(NetConn_NetHandle \*netHandle) | 获得默认激活的数据网络。 | 22| OH_NetConn_IsDefaultNetMetered(int32_t \*isMetered) | 检查当前网络上的数据流量使用是否被计量。 | 23| OH_NetConn_GetConnectionProperties(NetConn_NetHandle \*netHandle, NetConn_ConnectionProperties *prop) | 获取netHandle对应的网络的连接信息。 | 24| OH_NetConn_GetNetCapabilities (NetConn_NetHandle \*netHandle, NetConn_NetCapabilities \*netCapacities) | 获取netHandle对应的网络的能力信息。 | 25| OH_NetConn_GetDefaultHttpProxy (NetConn_HttpProxy \*httpProxy) | 获取网络默认的代理配置信息。 如果设置了全局代理,则会返回全局代理配置信息。如果进程已经绑定到指定netHandle对应的网络,则返回网络句柄对应网络的代理配置信息。在其它情况下,将返回默认网络的代理配置信息。 | 26| OH_NetConn_GetAddrInfo (char \*host, char \*serv, struct addrinfo \*hint, struct addrinfo \*\*res, int32_t netId) | 通过netId获取DNS结果。 | 27| OH_NetConn_FreeDnsResult(struct addrinfo \*res) | 释放DNS结果内存。 | 28| OH_NetConn_GetAllNets(NetConn_NetHandleList \*netHandleList) | 获取所有处于连接状态的网络列表。 | 29| OHOS_NetConn_RegisterDnsResolver(OH_NetConn_CustomDnsResolver resolver) | 注册自定义dns解析器。<br/>**弃用:** 从API version 13开始废弃。<br/>**替代:** 推荐使用OH_NetConn_RegisterDnsResolver。| 30| OHOS_NetConn_UnregisterDnsResolver(void) | 取消注册自定义dns解析器。<br/>**弃用:** 从API version 13开始废弃。<br/>**替代:** 推荐使用OH_NetConn_UnregisterDnsResolver。| 31| OH_NetConn_RegisterDnsResolver(OH_NetConn_CustomDnsResolver resolver) | 注册自定义dns解析器。 | 32| OH_NetConn_UnregisterDnsResolver(void) | 取消注册自定义dns解析器。| 33| OH_NetConn_SetPacUrl(const char \*pacUrl) | 设置系统级代理自动配置(PAC)脚本地址。 | 34| OH_NetConn_GetPacUrl(char \*pacUrl) | 获取系统级代理自动配置(PAC)脚本地址。 | 35| OH_NetConn_QueryProbeResult(char *destination, int32_t duration, NetConn_ProbeResultInfo *probeResultInfo)| 查询探测结果。 | 36| OH_NetConn_QueryTraceRoute(char *destination, NetConn_TraceRouteOption *option, NetConn_TraceRouteInfo *traceRouteInfo)| 查询跟踪路由。 | 37 38## 网络管理接口开发示例 39 40### 开发步骤 41 42使用本文档涉及接口获取网络相关信息时,需先创建Native C++工程,在源文件中将相关接口封装,再在ArkTs层对封装的接口进行调用,使用hilog或者console.log等手段选择打印在控制台或者生成设备日志。 43 44本文以实现获取默认激活的数据网络为例,给出具体的开发指导。 45 46其他接口开发请参考:[完整示例代码](https://gitcode.com/openharmony/applications_app_samples/tree/master/code/DocsSample/NetWork_Kit/NetWorkKit_NetManager/NetConnection_Exploitation_case)。 47 48### 添加开发依赖 49 50**添加动态链接库** 51 52CMakeLists.txt中添加以下lib: 53 54```txt 55libace_napi.z.so 56libnet_connection.so 57``` 58 59**头文件** 60 61```c 62#include "napi/native_api.h" 63#include "network/netmanager/net_connection.h" 64#include "network/netmanager/net_connection_type.h" 65``` 66 67### 构建工程 68 691. 在源文件中编写调用该API的代码,并将结果封装成一个`napi_value`类型的值返回给Node.js环境。 70 71```C 72// Get the execution results of the default network connection. 73static napi_value GetDefaultNet(napi_env env, napi_callback_info info) 74{ 75 size_t argc = 1; 76 napi_value args[1] = {nullptr}; 77 napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); 78 int32_t param; 79 napi_get_value_int32(env, args[0], ¶m); 80 81 NetConn_NetHandle netHandle; 82 if (param== 0) { 83 param= OH_NetConn_GetDefaultNet(NULL); 84 } else { 85 param= OH_NetConn_GetDefaultNet(&netHandle); 86 } 87 88 napi_value result; 89 napi_create_int32(env, param, &result); 90 return result; 91} 92 93// Get the ID of the default network connection. 94static napi_value NetId(napi_env env, napi_callback_info info) { 95 int32_t defaultNetId; 96 97 NetConn_NetHandle netHandle; 98 OH_NetConn_GetDefaultNet(&netHandle); 99 defaultNetId = netHandle.netId; // Get the default netId 100 101 napi_value result; 102 napi_create_int32(env, defaultNetId, &result); 103 104 return result; 105} 106``` 107 108简要说明:这两个函数用于获取系统默认网络连接的相关信息。其中,GetDefaultNet是接收ArkTs端传入的测试参数,返回调用接口后对应的返回值,param可以自行调整;如果返回值为0,代表获取成功,401代表参数错误,201代表没有权限;而NetId函数则用于获取默认网络连接的ID。这些信息可以用于进一步的网络操作。 109 110 1112. 将通过napi封装好的`napi_value`类型对象初始化导出,通过外部函数接口,将以上两个函数暴露给JavaScript使用。 112 113```C 114EXTERN_C_START 115static napi_value Init(napi_env env, napi_value exports) 116{ 117 // Information used to describe an exported attribute. Two properties are defined here: `GetDefaultNet` and `NetId`. 118 napi_property_descriptor desc[] = { 119 {"GetDefaultNet", nullptr, GetDefaultNet, nullptr, nullptr, nullptr, napi_default, nullptr}, 120 {"NetId", nullptr, NetId, nullptr, nullptr, nullptr, napi_default, nullptr}}; 121 napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); 122 return exports; 123} 124EXTERN_C_END 125``` 126 1273. 将上一步中初始化成功的对象通过`RegisterEntryModule`函数,使用`napi_module_register`函数将模块注册到Node.js中。 128 129```C 130static napi_module demoModule = { 131 .nm_version = 1, 132 .nm_flags = 0, 133 .nm_filename = nullptr, 134 .nm_register_func = Init, 135 .nm_modname = "entry", 136 .nm_priv = ((void*)0), 137 .reserved = { 0 }, 138}; 139 140extern "C" __attribute__((constructor)) void RegisterEntryModule(void) 141{ 142 napi_module_register(&demoModule); 143} 144``` 145 1464. 在工程的index.d.ts文件中定义两个函数的类型。 147 148- GetDefaultNet函数接受一个数字参数code,返回一个数字类型的值。 149- NetId函数不接受参数,返回一个数字类型的值。 150 151```ts 152export const GetDefaultNet: (code: number) => number; 153export const NetId: () => number; 154``` 155 1565. 在index.ets文件中对上述封装好的接口进行调用。 157 158```ts 159import testNetManager from 'libentry.so'; 160 161@Entry 162@Component 163struct Index { 164 @State message: string = ''; 165 166 build() { 167 Row() { 168 Column() { 169 Text(this.message) 170 .fontSize(50) 171 .fontWeight(FontWeight.Bold) 172 Button('GetDefaultNet').onClick(event => { 173 this.GetDefaultNet(); 174 }) 175 Button('CodeNumber').onClick(event =>{ 176 this.CodeNumber(); 177 }) 178 } 179 .width('100%') 180 } 181 .height('100%') 182 } 183 184 GetDefaultNet() { 185 let netid = testNetManager.NetId(); 186 console.log("The defaultNetId is [" + netid + "]"); 187 } 188 189 CodeNumber() { 190 let testParam = 0; 191 let codeNumber = testNetManager.GetDefaultNet(testParam); 192 if (codeNumber === 0) { 193 console.log("Test success. [" + codeNumber + "]"); 194 } else if (codeNumber === 201) { 195 console.log("Missing permissions. [" + codeNumber + "]"); 196 } else if (codeNumber === 401) { 197 console.log("Parameter error. [" + codeNumber + "]"); 198 } 199 } 200} 201 202``` 203 2046. 配置`CMakeLists.txt`,本模块需要用到的共享库是`libnet_connection.so`,在工程自动生成的`CMakeLists.txt`中的`target_link_libraries`中添加此共享库。 205 206> **注意:** 207> 208> 如图所示,在`add_library`中的`entry`是工程自动生成的`modename`。若要做修改,需和步骤3中`.nm_modname`保持一致。 209 210 211 212经过以上步骤,整个工程的搭建已经完成,接下来就可以连接设备运行工程进行日志查看了。 213 214## 测试步骤 215 2161. 连接设备,使用DevEco Studio打开搭建好的工程。 217 2182. 运行工程,设备上会弹出以下所示图片。 219 220- 点击`GetDefaultNet`时获取的是默认网络ID。 221- 点击`codeNumber`时获取的是接口返回的响应状态码。 222 223 224 2253. 点击`GetDefaultNet`按钮,控制台会打印日志。 226 227 228 2294. 点击`codeNumber`按钮,控制台会打印相应的响应状态码。 230 231 232 233## 相关实例 234 235针对网络连接的开发,可参考相关实例:[NetConnection开发指导](https://gitcode.com/openharmony/applications_app_samples/tree/master/code/DocsSample/NetWork_Kit/NetWorkKit_NetManager/NetConnection_Exploitation_case)。 236