The below code helps to get the IPv4 and IPv6 Address using Kotlin.
Happy Coding :-)
import java.net.NetworkInterface import java.util.* /* * Author: Rajendhiran E * Date: 21-Jan-2018 * */ object IPHelper { val IPV4Address: String get() = getIPAddress(true) val IPV6Address: String get() = getIPAddress(false) /** * Get IP address from first non-localhost interface * @param userIPV4 true=return ipv4, false=return ipv6 * @return address or empty string */ private fun getIPAddress(userIPV4: Boolean): String { try { Collections.list(NetworkInterface.getNetworkInterfaces()).forEach { Collections.list(it.inetAddresses).forEach { if (!it.isLoopbackAddress) { val sAddr = it.hostAddress val isIPv4 = sAddr.indexOf(':') < 0 if (userIPV4) { if (isIPv4) { return sAddr } } else { if (!isIPv4) { val delim = sAddr.indexOf('%') return if (delim < 0) sAddr.toUpperCase() else sAddr.substring(0, delim).toUpperCase() } } } } } } catch (ignored: Exception) { } return "" } }
println("IP Address V4 - ${IPHelper.IPV4Address}") println("IP Address V6 - ${IPHelper.IPV6Address}")
Output Console IP Address v4 - 192.168.240.2 IP Address v6 - FE80:0:0:0:4D9:5C92:3433:8A6B
Happy Coding :-)