Skip to content

Commit

Permalink
Merge pull request #58 from capcom6/issue/52-local-ip-tethering
Browse files Browse the repository at this point in the history
Try to get local IP from iface in tethering mode
  • Loading branch information
capcom6 committed Apr 17, 2024
2 parents 96dffb3 + 68f26c0 commit 047bc38
Showing 1 changed file with 38 additions and 13 deletions.
51 changes: 38 additions & 13 deletions app/src/main/java/me/capcom/smsgateway/providers/LocalIPProvider.kt
Original file line number Diff line number Diff line change
@@ -1,29 +1,54 @@
package me.capcom.smsgateway.providers

import android.content.Context
import android.content.Context.WIFI_SERVICE
import android.net.wifi.WifiManager
import java.math.BigInteger
import java.net.InetAddress
import java.nio.ByteOrder
import java.net.Inet4Address
import java.net.NetworkInterface


class LocalIPProvider(private val context: Context): IPProvider {
override suspend fun getIP(): String? {
return try {
var ipAddress =
(context.applicationContext.getSystemService(WIFI_SERVICE) as WifiManager).connectionInfo.ipAddress
// Convert little-endian to big-endianif needed
if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) {
ipAddress = Integer.reverseBytes(ipAddress)
try {
val wifiManager =
context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager

// If the device is in tethering mode, the following method may return null or a default IP
wifiManager.connectionInfo?.let { connectionInfo ->
val ipInt = connectionInfo.ipAddress
if (ipInt != 0) {
return (ipInt and 0xFF).toString() + "." +
((ipInt shr 8) and 0xFF) + "." +
((ipInt shr 16) and 0xFF) + "." +
((ipInt shr 24) and 0xFF)
}
}

val ipByteArray: ByteArray = BigInteger.valueOf(0L + ipAddress).toByteArray()
// If the above doesn't work, try to find the WiFi network interface directly
val wifiInterface = NetworkInterface.getNetworkInterfaces().asSequence()
.find { it.name.contains("wlan", ignoreCase = true) }

wifiInterface?.inetAddresses?.asSequence()
?.find { !it.isLoopbackAddress && it is Inet4Address }
?.let { inetAddress ->
return inetAddress.hostAddress
}

(InetAddress.getByAddress(ipByteArray).hostAddress)
// Check any other network interface
val interfaces = NetworkInterface.getNetworkInterfaces()
while (interfaces.hasMoreElements()) {
val intf = interfaces.nextElement()
val addrs = intf.inetAddresses
while (addrs.hasMoreElements()) {
val addr = addrs.nextElement()
if (!addr.isLoopbackAddress && addr is Inet4Address) {
return addr.hostAddress
}
}
}
} catch (e: Exception) {
e.printStackTrace()
null
}

return null
}
}

0 comments on commit 047bc38

Please sign in to comment.