import { connection } from '@kit.NetworkKit';
@Entry
@Component
struct SubnetMask {
@State subnetMaskStr: string = '获取子网掩码';
/**
* 计算子网掩码
* @param prefixLength 前缀长度
* @returns 子网掩码字符串
*/
calculateSubnetMask(prefixLength: number): string {
if (!Number.isInteger(prefixLength) || prefixLength > 32 || prefixLength < 0) {
return '';
}
// 计算每个字节的子网掩码部分
let subnetMask = '';
for (let i = 0; i < 4; i++) {
// 每个字节中的有效位数
const bits = Math.min(prefixLength, 8);
// 计算子网掩码字节的值并添加到结果字符串
subnetMask += (256 - Math.pow(2, 8 - bits)) + '.';
// 更新剩余的位数
prefixLength -= bits;
}
// 去除末尾的点并返回子网掩码字符串
return subnetMask.slice(0, -1);
}
build() {
RelativeContainer() {
Text(this.subnetMaskStr)
.id('SubnetMaskHelloWorld')
.fontSize($r('app.float.page_text_font_size'))
.fontWeight(FontWeight.Bold)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
.onClick(()=>{
try {
// 1.获取默认网络
const netHandle = connection.getDefaultNetSync();
// 2.获取网络连接信息
const connectionProperties = connection.getConnectionPropertiesSync(netHandle);
// 3.提取链路信息
const linkAddress = connectionProperties.linkAddresses?.[0];
if (linkAddress) {
// 计算子网掩码,参数为链路地址前缀的长度
this.subnetMaskStr = this.calculateSubnetMask(linkAddress.prefixLength);
}
} catch (err) {
console.error(`errCode is ${err.code}, message is ${err.message}`);
}
})
}
.height('100%')
.width('100%');
}
} 示例效果:
