Skip to content

Instantly share code, notes, and snippets.

@arindamxd
Created August 8, 2019 10:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arindamxd/8bfa199c25de20bba426b094097d8b66 to your computer and use it in GitHub Desktop.
Save arindamxd/8bfa199c25de20bba426b094097d8b66 to your computer and use it in GitHub Desktop.
Fetch IP Address
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