HarmonyOS鸿蒙Next中如何获取热点的ip地址,wifi网络的ip地址以及5G网段的ip地址
HarmonyOS鸿蒙Next中如何获取热点的ip地址,wifi网络的ip地址以及5G网段的ip地址 如何获取热点的ip地址,wifi网络的ip地址以及5G网段的ip地址?
手机连接WiFi后,获取当前手机的IP地址: 使用wifiManager模块获取ipInfo,然后转换为IP常用格式,注意wifiManager.getIpInfo()接口需要权限 ohos.permission.GET_WIFI_INFO。
https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs-V5/faqs-network-10-V5
获取连接WIFI的IP地址: wifiManager.getLinkedInfo返回参数ipAddress。 注意:
- 需要权限ohos.permission.GET_WIFI_INFO
- 需要通过位移符转化为常见的ip地址格式,可参考如下:
import { wifiManager } from '@kit.ConnectivityKit';
@Entry
@Component
struct Address {
@State message: string = '获取IP地址';
build() {
RelativeContainer() {
Button(this.message)
.id('address')
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
.onClick(() =>{
wifiManager.getLinkedInfo((err, data) => {
if (err) {
console.error("get linked info error");
return;
}
});
let info = wifiManager.getIpInfo()
let ipAddress = info.ipAddress;
let ip = (ipAddress >>> 24) + "." + (ipAddress >> 16 & 0xFF) + "." + (ipAddress >> 8 & 0xFF) + "." + (ipAddress & 0xFF);
console.info("IP信息:" + JSON.stringify(info));
console.info("IP地址:" + JSON.stringify(ip));
})
}
.height('100%')
.width('100%')
}
}
获取5G网段的ip地址: 可以使用getConnectionPropertiesSync返回结果的ConnectionProperties.linkAddresses属性获取
更多关于HarmonyOS鸿蒙Next中如何获取热点的ip地址,wifi网络的ip地址以及5G网段的ip地址的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙Next中,获取热点的IP地址、WiFi网络的IP地址以及5G网段的IP地址可以通过NetManager
和NetAddress
类实现。以下为具体方法:
-
获取热点的IP地址:
- 使用
NetManager
获取当前网络连接信息。 - 通过
NetAddress
获取热点的IP地址。
import net from '[@ohos](/user/ohos).net.ethernet'; let netManager = net.getDefaultNet(); let addresses = netManager.getAddresses(); let hotspotIp = addresses[0].address;
- 使用
-
获取WiFi网络的IP地址:
- 使用
NetManager
获取WiFi连接信息。 - 通过
NetAddress
获取WiFi的IP地址。
import net from '[@ohos](/user/ohos).net.wifi'; let wifiManager = net.getDefaultNet(); let addresses = wifiManager.getAddresses(); let wifiIp = addresses[0].address;
- 使用
-
获取5G网段的IP地址:
- 使用
NetManager
获取5G网络连接信息。 - 通过
NetAddress
获取5G的IP地址。
import net from '[@ohos](/user/ohos).net.cellular'; let cellularManager = net.getDefaultNet(); let addresses = cellularManager.getAddresses(); let cellularIp = addresses[0].address;
- 使用
以上代码片段展示了如何在HarmonyOS鸿蒙Next中获取不同网络类型的IP地址。
在HarmonyOS鸿蒙Next中,可以通过NetworkInterface
类获取设备的网络信息。首先,使用NetworkInterface.getByName()
方法获取指定网络接口(如WiFi、5G),然后通过getInetAddresses()
方法获取IP地址列表。对于热点,通常使用“wlan0”或“ap0”接口。代码示例如下:
NetworkInterface wifiInterface = NetworkInterface.getByName("wlan0");
for (InetAddress address : Collections.list(wifiInterface.getInetAddresses())) {
if (address instanceof Inet4Address) {
String ip = address.getHostAddress();
// 处理IP地址
}
}
类似地,替换接口名称可获取5G或热点的IP地址。