Reputation: 61
I am having an issue with getting every IP address in Java. When I open the GUI to select which IP you want to use, I call:
private List<String> getIP() {
List<String> outputList = new ArrayList<String>();
try {
InetAddress localIP = InetAddress.getLocalHost();
InetAddress[] everyIPAddress = InetAddress.getAllByName(localIP
.getCanonicalHostName());
if (everyIPAddress != null && everyIPAddress.length > 1) {
for (int i = 0; i < everyIPAddress.length; i++) {
if (!everyIPAddress[i].toString().contains(":")) {
outputList.add(everyIPAddress[i].toString());
}
}
}
} catch (UnknownHostException e) {
System.out.println("Error finding IP Address");
}
return outputList;
}
This method gets all of the IPv4 addresses that the client has. I know IPv6 addresses contain colons, so I don't add any with a colon to the list.
Then, pressing the button changes the IP address. However, I have noticed that when there is only one IPv4 address that the machine has (You get two from having a service like Hamachi) it will return a null exception. How would I go about getting every IP address of the client without returning a null exception if there is only one address?
Upvotes: 1
Views: 174
Reputation: 8269
if (everyIPAddress != null && everyIPAddress.length > 1) {
should be
if (everyIPAddress != null && everyIPAddress.length >= 1) {
or
if (everyIPAddress != null && everyIPAddress.length > 0) {
Upvotes: 4