简体   繁体   中英

Issue With Getting Every IP Address of the Client in Java

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?

if (everyIPAddress != null && everyIPAddress.length > 1) {

should be

if (everyIPAddress != null && everyIPAddress.length >= 1) {

or

if (everyIPAddress != null && everyIPAddress.length > 0) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM