-7

I want to implement a code which checks ip into array. I tried this:

        // 123.11.1.1, 123.1.1.12, 123.322.12.1
        String[] list = merchant.getAllowed_ip_address().split(",");

        String ip = request.getRemoteAddr();
        for (ip : list.split(",")) {
            if (!ip.trim().equals(request.getRemoteAddr().trim())) 
            {
               // Not in list
            }
        }

But I get Cannot invoke split(String) on the array type String[]. Do you know how I can fix this?

1
  • use split on the each item from the array Commented Feb 16, 2019 at 14:13

3 Answers 3

3

You can't do split on a list, once you split the string then you have an array of all the IPs then you can check

    // 123.11.1.1, 123.1.1.12, 123.322.12.1
    String[] list = merchant.getAllowed_ip_address().split(",");

    String ip = request.getRemoteAddr();

    for (String allowedIP : list) {
        if (!ip.trim().equals(allowedIP.trim())) {
            // Not in list
        }
    }

Also, you can do this for simplicity

String ip = request.getRemoteAddr();
boolean notExist = Arrays.stream(merchant.getAllowed_ip_address().split(","))
                .map(String::trim)
                .noneMatch(ip::equals);
Sign up to request clarification or add additional context in comments.

Comments

0
for (int i=0;i<list.length ;i++) {
            if (!ip.trim().equals(list[i].trim())) 
            {
               // Not in list
            }

You cannot call split on an array.The array already contains the spitted IP's. You just need to check if the value matches.

Comments

0

This sets the variable "inthelist" to true when the ip is in the list, to false otherwise. A strict equals comparison is done, that could be replaced with something more sophisticated if required.

    // 123.11.1.1, 123.1.1.12, 123.322.12.1
    String list = merchant.getAllowed_ip_address();
    String ip = request.getRemoteAddr().trim();
    boolean inthelist = false;
    for (String aip : list.split(",")) {
        if (aip.trim().equals(ip)) {
           inthelist=true;
           break;
        }
    }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.