|
1 | 1 | package dev.aikido.agent_api.helpers.net;
|
2 | 2 |
|
3 | 3 | import java.net.InetAddress;
|
4 |
| -import java.net.NetworkInterface; |
5 |
| -import java.net.SocketException; |
6 |
| -import java.util.Enumeration; |
| 4 | +import java.net.UnknownHostException; |
7 | 5 |
|
8 | 6 | public final class IPAddress {
|
9 |
| - private IPAddress() {} |
| 7 | + private IPAddress() { |
| 8 | + } |
10 | 9 |
|
11 | 10 | public static String getIpAddress() {
|
12 | 11 | try {
|
13 |
| - NetworkInterface bestInterface = null; |
14 |
| - |
15 |
| - Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); |
16 |
| - while (networkInterfaces.hasMoreElements()) { |
17 |
| - NetworkInterface networkInterface = networkInterfaces.nextElement(); |
| 12 | + String hostAddress = InetAddress.getLocalHost().getHostAddress(); |
18 | 13 |
|
19 |
| - // Check if the network interface is up and not a loop-back |
20 |
| - if (networkInterface.isUp() && !networkInterface.isLoopback()) { |
21 |
| - // Check if it has at least one valid IP address |
22 |
| - Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses(); |
23 |
| - while (inetAddresses.hasMoreElements()) { |
24 |
| - InetAddress inetAddress = inetAddresses.nextElement(); |
25 |
| - if (!inetAddress.isLoopbackAddress()) { // Check if the address is not a loop-back address |
26 |
| - bestInterface = networkInterface; |
27 |
| - break; // Found a valid interface, no need to check further |
28 |
| - } |
29 |
| - } |
30 |
| - } |
| 14 | + // Remove the zone index if present |
| 15 | + if (hostAddress.contains("%")) { |
| 16 | + hostAddress = hostAddress.substring(0, hostAddress.indexOf('%')); |
31 | 17 | }
|
32 | 18 |
|
33 |
| - if (bestInterface != null) { |
34 |
| - Enumeration<InetAddress> inetAddresses = bestInterface.getInetAddresses(); |
35 |
| - while (inetAddresses.hasMoreElements()) { |
36 |
| - InetAddress inetAddress = inetAddresses.nextElement(); |
37 |
| - if (!inetAddress.isLoopbackAddress()) { |
38 |
| - return inetAddress.getHostAddress(); |
39 |
| - } |
40 |
| - } |
41 |
| - } |
42 |
| - } catch (SocketException ignored) {} |
| 19 | + return hostAddress; |
| 20 | + } catch (UnknownHostException ignored) { |
| 21 | + // pass-through |
| 22 | + } |
43 | 23 | return "0.0.0.0";
|
44 | 24 | }
|
45 | 25 | }
|
0 commit comments