[kotlin] get local IPv4 address

public ip가 아니라 192.168.1.100 같은 로컬의 ip를 얻어올 때 사용한다.

Internet 권한이 있어야 한다.

<uses-permission android:name="android.permission.INTERNET" />
private fun getIpAddress(): String {
  var result = ""
  NetworkInterface.getNetworkInterfaces().iterator().forEach { networkInterface ->
    networkInterface.inetAddresses.iterator().forEach {
      if (!it.isLoopbackAddress && isIPv4Address(it.hostAddress)) {
        result = it.hostAddress
      }
    }
  }
  return result
}

private fun isIPv4Address(address: String): Boolean {
  return if (address.isEmpty()) {
    false
  } else try {
    InetAddress.getByName(address) is Inet4Address
  } catch (exception: UnknownHostException) {
    false
  }
}