Hi Satya,
The error you're seeing:
java.lang.NullPointerException: Cannot invoke "java.net.Inet4Address.toString()" because "<local2>[<local5>]" is null
...indicates that your inetAddressArray contains null values. This happens because you're pre-allocating an array of size inetAddresses.length and only partially filling it when the address is IPv4. So, unused slots remain null, and later, you attempt to call .toString() on them.
as for the solution,
You should not pre-allocate the array and instead use a dynamic structure like a List to store only the non-null IPv4 addresses.
you can use a code something like this (sample code, you can make changes accordingly),
@java.lang.Overridepublic java.lang.String executeAction() throws Exception { // BEGIN USER CODE try { InetAddress[] inetAddresses = InetAddress.getAllByName(InputHostName); if (inetAddresses == null || inetAddresses.length == 0) { return ""; }
List<String> ipv4Addresses = new ArrayList<>();
for (InetAddress address : inetAddresses) { if (address instanceof java.net.Inet4Address) { String ip = address.getHostAddress(); // safer and cleaner than toString + substring ipv4Addresses.add(ip); } }
if (ipv4Addresses.isEmpty()) { return ""; // or return "No IPv4 address found" }
return String.join(",", ipv4Addresses);
} catch (UnknownHostException ex) { return ""; } // END USER CODE}
Let me know, if you have any issues,
Hope it helps!
Is your for loop correct? It looks like you are incrementing variable i before using it (++i instead of i++), so it will be one more than the size of your array on its last iteration, giving you the null error.