Java IP Address Get getLocalIPv6Address()

Here you can find the source of getLocalIPv6Address()

Description

get Local I Pv Address

License

Apache License

Declaration

public static String getLocalIPv6Address() throws IOException 

Method Source Code


//package com.java2s;
/*//from  w  w w. j a v  a2 s  .  co m
 * Copyright 2007-2107 the original author or authors.
 *
 * 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.
 */

import java.io.IOException;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;

import java.util.Enumeration;

public class Main {

    public static String getLocalIPv6Address() throws IOException {
        InetAddress inetAddress = null;
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        outer: while (networkInterfaces.hasMoreElements()) {
            Enumeration<InetAddress> inetAds = networkInterfaces.nextElement().getInetAddresses();
            while (inetAds.hasMoreElements()) {
                inetAddress = inetAds.nextElement();
                // Check if it's ipv6 address and reserved address
                if (inetAddress instanceof Inet6Address && !isReservedAddr(inetAddress)) {
                    break outer;
                }
            }
        }
        String ipAddr = inetAddress.getHostAddress();
        // Filter network card No
        int index = ipAddr.indexOf('%');
        if (index > 0) {
            ipAddr = ipAddr.substring(0, index);
        }
        return ipAddr;
    }

    /**
     * Check if it's "local address" or "link local address" or "loopbackaddress"
     * 
     * @param ip address
     * @return result
     */
    private static boolean isReservedAddr(InetAddress inetAddr) {
        if (inetAddr.isAnyLocalAddress() || inetAddr.isLinkLocalAddress() || inetAddr.isLoopbackAddress()) {
            return true;
        }
        return false;
    }
}

Related

  1. getLocalIPs()
  2. getLocalIPs()
  3. getLocalIps()
  4. getLocalIPs(boolean refresh)
  5. getLocalIpv4()
  6. getLocalNetWorkIp()
  7. getLocalV4Ip()
  8. getLocalV4IpList()
  9. getLongIp(byte[] buff)