Java: check if an IP address exists in a list of arrays

Is there a specific way to check if an IP address exists in an array? Right now I have an arraylist that consists of strings of IP addresses (eg "192.168.0.4", etc.). After receiving the packet, I would like to check if the IP of the packet belongs to the arraylist.

At first I thought this would be enough:

for (int i = 0; i < myList.size(); i++)
{
  if (packet.getAddress().equals(InetAddress.getByName(myList.get(i))))
  {
    System.out.println("this packet IP address is in list");
  }

  else
  {
    System.out.println("this packet IP address is not in list!");
  }

      

I thought the else statement would solve this situation, but I was wrong. Any suggestions would be appreciated.

+3


source to share


3 answers


You must check the entire list before you know the IP does not exist:



boolean found = false;
for (int i = 0; i < myList.size() && !found; i++) {
    if (packet.getAddress().equals(InetAddress.getByName(myList.get(i)))) {
        found = true;
        System.out.println("this packet IP address is in list");
    }
}
if (!found) {
    System.out.println("this packet IP address is not in list!");
}

      

+2


source


I would suggest converting the ArrayList to a Set (not before every check as that would be unnecessary overhead) so you can avoid the for loop. It's just a question

Set<InetAddress> mySet = new HashSet<InetAddress>(myList);
...
if(mySet.contains(packet.getAddress())) {
 // ...
}

      



I think you can also use myList.contains, but I think the implementation will still loop through the list, so using Set will be faster.

+4


source


The problem is you are printing a message for every item that doesn't match the address. Instead, you can encapsulate this functionality into a method, return a boolean, and then print:

public boolean isPackedInList() {
    for (int i = 0; i < myList.size(); i++) {
        if (packet.getAddress().equals(InetAddress.getByName(myList.get(i)))) {
            return true;
        }
    }
    return false;
}

      

And then use it:

if (isPackedInList()) {
    System.out.println("this packet IP address is in list");
} else {
    System.out.println("this packet IP address is not in list!");
}

      

+1


source







All Articles