Skip to content

Commit e3466bf

Browse files
committed
Utils: Added methods to retrieve IPs and NICs
- Added method getIPv4ForInterface(NetworkInterface) and getIPv4ForInterface(String) which returns a list of ip4 addresses given a NetworkInterface instance/String name of interface; - Added method getAvailableNICs(Boolean, Boolean) and getAvailableNICs() which return a list of NetworkInterface instances that represents available NICs on the system;
1 parent 2cda0f5 commit e3466bf

File tree

1 file changed

+66
-0
lines changed
  • app/src/main/java/net/christianbeier/droidvnc_ng

1 file changed

+66
-0
lines changed

app/src/main/java/net/christianbeier/droidvnc_ng/Utils.kt

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,10 @@ import java.io.InputStreamReader
1717
import java.util.concurrent.locks.Lock
1818
import kotlin.concurrent.withLock
1919

20+
import java.net.InterfaceAddress;
21+
import java.net.NetworkInterface;
22+
import java.net.SocketException;
23+
2024
object Utils {
2125

2226
@JvmStatic
@@ -102,6 +106,7 @@ object Utils {
102106
directory.deleteRecursively()
103107
}
104108

109+
105110
/**
106111
* Rename a file. Does not overwrite!
107112
*/
@@ -139,4 +144,65 @@ object Utils {
139144
}
140145
}
141146

147+
148+
@JvmStatic
149+
fun getAvailableNICs(upIfOnly: Boolean, ipAvailOnly: Boolean): ArrayList<NetworkInterface> {
150+
val nics = ArrayList<NetworkInterface>();
151+
152+
try {
153+
// Thanks go to https://stackoverflow.com/a/20103869/361413
154+
val nis = NetworkInterface.getNetworkInterfaces();
155+
while (nis.hasMoreElements()) {
156+
val ni = nis.nextElement();
157+
if (upIfOnly) {
158+
if (ipAvailOnly) {
159+
// Check if there are actual ipv4 addresses, if so, add the NetworkInterface
160+
// Should we consider IPv6 also? Technically yes, but the program, at the moment, does not support them.
161+
for (ia in ni.getInterfaceAddresses()) {
162+
if (ia.getAddress().getAddress().count() == 4) {
163+
nics.add(ni);
164+
break;
165+
}
166+
}
167+
} else {
168+
nics.add(ni);
169+
}
170+
} else {
171+
nics.add(ni);
172+
}
173+
}
174+
} catch (e: SocketException) {
175+
//unused
176+
}
177+
178+
return nics;
179+
}
180+
181+
182+
@JvmStatic
183+
fun getAvailableNICs(): ArrayList<NetworkInterface> {
184+
return getAvailableNICs(false, true);
185+
}
186+
187+
188+
@JvmStatic
189+
fun getIPv4ForInterface(ni: String): ArrayList<String>{
190+
return getIPv4ForInterface(NetworkInterface.getByName(ni));
191+
}
192+
193+
194+
@JvmStatic
195+
fun getIPv4ForInterface(ni: NetworkInterface): ArrayList<String>{
196+
val ipv4s = ArrayList<String>();
197+
198+
for (ia in ni.getInterfaceAddresses()) {
199+
//filter for ipv4/ipv6
200+
if (ia.getAddress().getAddress().count() == 4) {
201+
//4 for ipv4, 16 for ipv6
202+
ipv4s.add(ia.getAddress().toString().replace("/", ""));
203+
}
204+
}
205+
206+
return ipv4s;
207+
}
142208
}

0 commit comments

Comments
 (0)