HarmonyOS socket绑定端口失败?

socket绑定端口失败,报错:“Address not available”

代码:

let ipAddress: socket.NetAddress = {
  address: '172.16.3.17',
  port: 9100
}

udpSocket.bind(ipAddress, (err: BusinessError) => {
  if (err) {  // err信息:"Address not available"
    console.log('bind fail')
    return
  }
  console.log('bind success')
})
阅读 569
1 个回答

ip地址错误也会造成这种问题,socket的bind函数入参地址是本机IP,本机ip获取案例参考:

import wifiManager from '@ohos.wifiManager';

let localAddress = resolveIP(wifiManager.getIpInfo().ipAddress);

export function resolveIP(ip: number): string {
  if (ip < 0 || ip > 0xFFFFFFFF) {
    throw ('The number is not normal!');
  }

  return (ip >>> 24) + '.' + (ip >> 16 & 0xFF) + '.' + (ip >> 8 & 0xFF) + '.' + (ip & 0xFF);
}

export function 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);
}