HarmonyOS鸿蒙Next开发中如何获取手机IP地址
HarmonyOS鸿蒙Next开发中如何获取手机IP地址 如何获取手机IP地址
3 回复
可以使用connection获取,参考下面demo
import connection from '@ohos.net.connection';
import hilog from '@ohos.hilog';
import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
const TAG: string = 'testTag'
/**
* 获取设备ip
*/
async function getLocalIp() {
try {
hilog.info(0x00000, TAG, '判断是否存在激活的网络连接');
let hasNet = connection.hasDefaultNetSync()
if (hasNet) {
hilog.info(0x00000, TAG, '存在默认激活的网络');
} else {
hilog.error(0x00000, TAG, '不存在激活的网络');
return
}
let handleResult = await connection.getDefaultNet()
if (handleResult) {
let connectionProperties = await connection.getConnectionProperties(handleResult)
if (connectionProperties && connectionProperties.linkAddresses) {
connectionProperties.linkAddresses.forEach((address: connection.LinkAddress, index: number) => {
hilog.info(0x00000, TAG, '索引:' + index + ',值:' + JSON.stringify(address));
})
}
}
} catch (e) {
hilog.error(0x00000, TAG, `获取网络信息出现异常,异常信息 %{public}s`, JSON.stringify(e) ?? '');
}
}
@Entry
@Component
struct getLocalIpTest {
@State message: string = 'Hello World';
context = this as common.UIAbilityContext;
build() {
RelativeContainer() {
Text(this.message)
.id('HelloWorld')
.fontSize(50)
.fontWeight(FontWeight.Bold)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
.onClick(() =>{
getLocalIp()
})
}
.height('100%')
.width('100%')
}
}
还需要配置下权限
{
'name': "ohos.permission.INTERNET"
},
{
'name': "ohos.permission.GET_NETWORK_INFO"
},
更多关于HarmonyOS鸿蒙Next开发中如何获取手机IP地址的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙Next开发中,获取手机IP地址可以通过使用[@ohos](/user/ohos).net.connection模块中的getDefaultNet和getIpInfo方法来实现。具体步骤如下:
-
导入
[@ohos](/user/ohos).net.connection模块:import connection from '[@ohos](/user/ohos).net.connection'; -
使用
getDefaultNet方法获取默认网络连接:let defaultNet = connection.getDefaultNetSync(); -
使用
getIpInfo方法获取IP地址信息:let ipInfo = defaultNet.getIpInfo(); -
从
ipInfo中提取IP地址:let ipAddress = ipInfo.ipAddress;
完整代码示例:
import connection from '[@ohos](/user/ohos).net.connection';
let defaultNet = connection.getDefaultNetSync();
let ipInfo = defaultNet.getIpInfo();
let ipAddress = ipInfo.ipAddress;
console.log("IP Address: " + ipAddress);
通过上述步骤,你可以在HarmonyOS鸿蒙Next开发中获取到手机的IP地址。
在HarmonyOS鸿蒙Next中,可以通过使用NetworkManager类来获取手机的IP地址。首先,确保在config.json中添加ohos.permission.GET_NETWORK_INFO权限。然后,使用NetworkManager.getInstance().getActiveNetworkInfo()获取当前网络信息,并调用getIpAddress()方法获取IP地址。示例代码如下:
NetworkInfo networkInfo = NetworkManager.getInstance().getActiveNetworkInfo();
String ipAddress = networkInfo.getIpAddress();
Log.info("IP Address: " + ipAddress);
此代码将输出当前设备的IP地址。

