Created
August 8, 2019 10:25
-
-
Save arindamxd/8bfa199c25de20bba426b094097d8b66 to your computer and use it in GitHub Desktop.
Fetch IP Address
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
internal fun getIpAddress(useIPv4: Boolean = true): String { | |
try { | |
val interfaces = Collections.list(getNetworkInterfaces()) | |
for (network in interfaces) { | |
val addresses = Collections.list(network.inetAddresses) | |
for (address in addresses) { | |
if (!address.isLoopbackAddress) { | |
val sAddress = address.hostAddress | |
var isIPv4: Boolean | |
isIPv4 = sAddress.indexOf(':') < 0 | |
if (useIPv4) { | |
if (isIPv4) | |
return sAddress | |
} else { | |
if (!isIPv4) { | |
val delim = sAddress.indexOf('%') // drop ip6 zone suffix | |
return if (delim < 0) { | |
sAddress.toUpperCase() | |
} else { | |
sAddress.substring(0, delim).toUpperCase() | |
} | |
} | |
} | |
} | |
} | |
} | |
} catch (e: Exception) { | |
logStackTrace(e) | |
} | |
return "" | |
} | |
internal fun getNewIpAddress(): String { | |
var result = "" | |
return try { | |
val pattern = Pattern.compile("^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$") | |
val interfaces = Collections.list(getNetworkInterfaces()) | |
val rmnetList = interfaces.filter { it.name.startsWith("rmnet") }.sortedBy { it.name } | |
val wlanList = interfaces.filter { it.name.startsWith("wlan") } | |
loop@ for (rmnet in rmnetList) { | |
val addresses = Collections.list(rmnet.inetAddresses) | |
for (address in addresses) { | |
if (!address.isLoopbackAddress && pattern.matcher(address.hostAddress).matches()) { | |
result = address.hostAddress | |
break@loop | |
} | |
} | |
} | |
loop@ for (wlan in wlanList) { | |
val addresses = Collections.list(wlan.inetAddresses) | |
for (address in addresses) { | |
if (!address.isLoopbackAddress && pattern.matcher(address.hostAddress).matches()) { | |
result = address.hostAddress | |
break@loop | |
} | |
} | |
} | |
result | |
} catch (e: Exception) { | |
logStackTrace(e) | |
result | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment