Java IP Address Get getFirstLocalNonLoopbackIpAddress()

Here you can find the source of getFirstLocalNonLoopbackIpAddress()

Description

get First Local Non Loopback Ip Address

License

Apache License

Declaration

public static String getFirstLocalNonLoopbackIpAddress() 

Method Source Code

//package com.java2s;
/*************************GO-LICENSE-START*********************************
 * Copyright 2014 ThoughtWorks, Inc.//from   www  . ja v  a 2s .  com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *************************GO-LICENSE-END***********************************/

import java.net.*;
import java.util.*;

public class Main {
    private static List<NetworkInterface> localInterfaces;

    public static String getFirstLocalNonLoopbackIpAddress() {
        SortedSet<String> addresses = new TreeSet<String>();
        Iterator<NetworkInterface> iterator = localInterfaces.iterator();
        while (iterator.hasNext()) {
            NetworkInterface networkInterface = iterator.next();
            Enumeration<InetAddress> inetAddressEnumeration = networkInterface.getInetAddresses();
            while (inetAddressEnumeration.hasMoreElements()) {
                InetAddress address = inetAddressEnumeration.nextElement();
                if (!address.isLoopbackAddress() && !address.getHostAddress().contains(":")) {
                    addresses.add(address.getHostAddress());
                }
            }
        }
        if (addresses.isEmpty()) {
            throw new RuntimeException("Failed to get non-loopback local ip address!");
        }
        return addresses.first();
    }
}

Related

  1. getExternalIp()
  2. getExternalIP(String host, String regexPattern)
  3. getExternalIPAddress()
  4. getExternalIPAddress()
  5. getExternalIPAddress()
  6. getFirstNonLoopbackAddress(boolean preferIpv4, boolean preferIPv6)
  7. getFirstNonLoopBackAddress(boolean preferIpv4, boolean preferIPv6)
  8. getHostIp()
  9. getHostIp()