HarmonyOS UDPSocket连接光猫路由器异常?

绑定地址的时候报这个错:

{"code":2301099,"message":"Address not available"}  

代码:

let bindAddr: socket.NetAddress = {
  address: 'xxx',
  port: xxx
}
this.udp.bind(bindAddr).then(() => {
  console.log('UDPSocket   bind success');
  let messageView = '';
  this.udp.on('message', (value: socket.SocketMessageInfo) => {
    for (let i: number = 0; i < value.message.byteLength; i++) {
      let uint8Array = new Uint8Array(value.message)
      let messages = uint8Array[i]
      let message = String.fromCharCode(messages);
      messageView += message;
    }
    console.log('UDPSocket on message message: ' + JSON.stringify(messageView));
    console.log('UDPSocket  remoteInfo: ' + JSON.stringify(value.remoteInfo));
    reject(messageView); // 解析并返回字符串
  });
  this.udp.on('error', (err: BusinessError) => {
    console.log("UDPSocket on error, err:" + JSON.stringify(err))
    reject(err); // 解析并返回字符串
  });
}).catch((err: BusinessError) => {
  console.log('UDPSocket bind fail'+JSON.stringify(err));
  reject(err); // 解析并返回字符串
});
阅读 492
1 个回答

socket的bind函数入参地址address指的是本地套接字路径,可以将address的值设置为本机的ip。

本机获取IP可参考如下代码:

import { wifi } from '@kit.ConnectivityKit';

@Entry
@Component
struct Index3 {
  @State message: string = 'Hello World';
  get() {
    let localAddress = this.resolveIP(wifi.getIpInfo().ipAddress) as string;
    console.log(`localAddress: ${localAddress}`);
    console.log(`ip校验结果为: ${this.checkIp(localAddress)}`);
  }

  resolveIP(ip: number): string {
    if (ip < 0 || ip > 0xFFFFFFFF) {
      console.log('The number is not normal!');
    }
    return (ip >>> 24) + '.' + (ip >> 16 & 0xFF) + '.' + (ip >> 8 & 0xFF) + '.' + (ip & 0xFF);
  }

  checkIp(ip: string): boolean {
    let ipRegex = /^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$/;
    return ipRegex.test(ip);
  }

  build() {
    Column() {
      Button('click').onClick(() => {
        this.get()
      })
    }.width('100%').height('100%').justifyContent(FlexAlign.Center)
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进