Skip to content

Commit 047bc38

Browse files
authored
Merge pull request #58 from capcom6/issue/52-local-ip-tethering
Try to get local IP from iface in tethering mode
2 parents 96dffb3 + 68f26c0 commit 047bc38

File tree

1 file changed

+38
-13
lines changed

1 file changed

+38
-13
lines changed
Lines changed: 38 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,54 @@
11
package me.capcom.smsgateway.providers
22

33
import android.content.Context
4-
import android.content.Context.WIFI_SERVICE
54
import android.net.wifi.WifiManager
6-
import java.math.BigInteger
7-
import java.net.InetAddress
8-
import java.nio.ByteOrder
5+
import java.net.Inet4Address
6+
import java.net.NetworkInterface
97

108

119
class LocalIPProvider(private val context: Context): IPProvider {
1210
override suspend fun getIP(): String? {
13-
return try {
14-
var ipAddress =
15-
(context.applicationContext.getSystemService(WIFI_SERVICE) as WifiManager).connectionInfo.ipAddress
16-
// Convert little-endian to big-endianif needed
17-
if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) {
18-
ipAddress = Integer.reverseBytes(ipAddress)
11+
try {
12+
val wifiManager =
13+
context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
14+
15+
// If the device is in tethering mode, the following method may return null or a default IP
16+
wifiManager.connectionInfo?.let { connectionInfo ->
17+
val ipInt = connectionInfo.ipAddress
18+
if (ipInt != 0) {
19+
return (ipInt and 0xFF).toString() + "." +
20+
((ipInt shr 8) and 0xFF) + "." +
21+
((ipInt shr 16) and 0xFF) + "." +
22+
((ipInt shr 24) and 0xFF)
23+
}
1924
}
2025

21-
val ipByteArray: ByteArray = BigInteger.valueOf(0L + ipAddress).toByteArray()
26+
// If the above doesn't work, try to find the WiFi network interface directly
27+
val wifiInterface = NetworkInterface.getNetworkInterfaces().asSequence()
28+
.find { it.name.contains("wlan", ignoreCase = true) }
29+
30+
wifiInterface?.inetAddresses?.asSequence()
31+
?.find { !it.isLoopbackAddress && it is Inet4Address }
32+
?.let { inetAddress ->
33+
return inetAddress.hostAddress
34+
}
2235

23-
(InetAddress.getByAddress(ipByteArray).hostAddress)
36+
// Check any other network interface
37+
val interfaces = NetworkInterface.getNetworkInterfaces()
38+
while (interfaces.hasMoreElements()) {
39+
val intf = interfaces.nextElement()
40+
val addrs = intf.inetAddresses
41+
while (addrs.hasMoreElements()) {
42+
val addr = addrs.nextElement()
43+
if (!addr.isLoopbackAddress && addr is Inet4Address) {
44+
return addr.hostAddress
45+
}
46+
}
47+
}
2448
} catch (e: Exception) {
2549
e.printStackTrace()
26-
null
2750
}
51+
52+
return null
2853
}
2954
}

0 commit comments

Comments
 (0)