I am developing an android application and need to get my device’s public IPV4 address to trigger an API, how can this be done. Some approaches I have tried I am sharing below

fun getIPAddress(): String? {
    try {
        val en = NetworkInterface.getNetworkInterfaces()
        while (en.hasMoreElements()) {
            val intf = en.nextElement()
            val enumIpAddr = intf.inetAddresses
            while (enumIpAddr.hasMoreElements()) {
                val inetAddress = enumIpAddr.nextElement()
                if (inetAddress is Inet4Address) {
                    return inetAddress.hostAddress
                }
            }
        }
    } catch (ex: SocketException) {
        ex.printStackTrace()
    }
    return ""
}

2nd Approach

fun getPublicIPv4Address(): String? {
    var publicIPAddress: String? = null
    try {
        val url = URL("https://api.ipify.org")
        val connection = url.openConnection() as HttpURLConnection
        connection.requestMethod = "GET"
        connection.connectTimeout = 5000
        connection.readTimeout = 5000
        val responseCode = connection.responseCode
        if (responseCode == HttpURLConnection.HTTP_OK) {
            val reader = BufferedReader(InputStreamReader(connection.inputStream))
            val response = StringBuilder()
            var line: String?
            while (reader.readLine().also { line = it } != null) {
                response.append(line)
            }
            reader.close()
            publicIPAddress = response.toString()
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }
    return publicIPAddress
}

In both these cases I am getting null values.