Java Code Examples for java.net.NetworkInterface#getInetAddresses()

The following examples show how to use java.net.NetworkInterface#getInetAddresses() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Util.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns a list of all the addresses on the system.
 * @param  inclLoopback
 *         if {@code true}, include the loopback addresses
 * @param  ipv4Only
 *         it {@code true}, only IPv4 addresses will be included
 */
static List<InetAddress> getAddresses(boolean inclLoopback,
                                      boolean ipv4Only)
    throws SocketException {
    ArrayList<InetAddress> list = new ArrayList<InetAddress>();
    Enumeration<NetworkInterface> nets =
             NetworkInterface.getNetworkInterfaces();
    for (NetworkInterface netInf : Collections.list(nets)) {
        Enumeration<InetAddress> addrs = netInf.getInetAddresses();
        for (InetAddress addr : Collections.list(addrs)) {
            if (!list.contains(addr) &&
                    (inclLoopback ? true : !addr.isLoopbackAddress()) &&
                    (ipv4Only ? (addr instanceof Inet4Address) : true)) {
                list.add(addr);
            }
        }
    }

    return list;
}
 
Example 2
Source File: NetWorkUtils.java    From Simpler with Apache License 2.0 6 votes vote down vote up
/**
 * 获取本机IP地址
 *
 * @return null:没有网络连接
 */
public static String getIpAddress() {
    try {
        NetworkInterface nerworkInterface;
        InetAddress inetAddress;
        for (Enumeration<NetworkInterface> en
             = NetworkInterface.getNetworkInterfaces();
             en.hasMoreElements(); ) {
            nerworkInterface = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr
                 = nerworkInterface.getInetAddresses();
                 enumIpAddr.hasMoreElements(); ) {
                inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
        return null;
    } catch (SocketException ex) {
        ex.printStackTrace();
        return null;
    }
}
 
Example 3
Source File: DnsUtil.java    From armeria with Apache License 2.0 6 votes vote down vote up
/**
 * Returns {@code true} if any {@link NetworkInterface} supports {@code IPv6}, {@code false} otherwise.
 */
public static boolean anyInterfaceSupportsIpV6() {
    try {
        final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            final NetworkInterface iface = interfaces.nextElement();
            final Enumeration<InetAddress> addresses = iface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                final InetAddress inetAddress = addresses.nextElement();
                if (inetAddress instanceof Inet6Address && !inetAddress.isAnyLocalAddress() &&
                    !inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress()) {
                    return true;
                }
            }
        }
    } catch (SocketException e) {
        logger.debug("Unable to detect if any interface supports IPv6, assuming IPv4-only", e);
    }
    return false;
}
 
Example 4
Source File: PayUtils.java    From PayAndroid with Apache License 2.0 6 votes vote down vote up
/**
 * 获取客户端ip
 * @return
 *      成功 ip
 *      失败 null
 */
public static String getIpAddress() {
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                    // if (!inetAddress.isLoopbackAddress() && inetAddress
                    // instanceof Inet6Address) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 5
Source File: Util.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns a list of all the addresses on the system.
 * @param  inclLoopback
 *         if {@code true}, include the loopback addresses
 * @param  ipv4Only
 *         it {@code true}, only IPv4 addresses will be included
 */
static List<InetAddress> getAddresses(boolean inclLoopback,
                                      boolean ipv4Only)
    throws SocketException {
    ArrayList<InetAddress> list = new ArrayList<InetAddress>();
    Enumeration<NetworkInterface> nets =
             NetworkInterface.getNetworkInterfaces();
    for (NetworkInterface netInf : Collections.list(nets)) {
        Enumeration<InetAddress> addrs = netInf.getInetAddresses();
        for (InetAddress addr : Collections.list(addrs)) {
            if (!list.contains(addr) &&
                    (inclLoopback ? true : !addr.isLoopbackAddress()) &&
                    (ipv4Only ? (addr instanceof Inet4Address) : true)) {
                list.add(addr);
            }
        }
    }

    return list;
}
 
Example 6
Source File: ProbeIB.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    Scanner s = new Scanner(new File(args[0]));
    try {
        while (s.hasNextLine()) {
            String link = s.nextLine();
            NetworkInterface ni = NetworkInterface.getByName(link);
            if (ni != null) {
                Enumeration<InetAddress> addrs = ni.getInetAddresses();
                while (addrs.hasMoreElements()) {
                    InetAddress addr = addrs.nextElement();
                    System.out.println(addr.getHostAddress());
                }
            }
        }
    } finally {
        s.close();
    }
}
 
Example 7
Source File: VenvyDeviceUtil.java    From VideoOS-Android-SDK with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 获取IP地址
 */
public static String getLocalIPAddress() {
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                .hasMoreElements(); ) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
                    .hasMoreElements(); ) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress() && (inetAddress instanceof Inet4Address)) {
                    return inetAddress.getHostAddress();
                }
            }
        }
    } catch (Exception ex) {
        VenvyLog.e(TAG, ex);
    }
    return null;
}
 
Example 8
Source File: SignalInfo.java    From MobileInfo with Apache License 2.0 6 votes vote down vote up
private static String getNetIP() {
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet6Address && !inetAddress.isLinkLocalAddress()) {
                    return inetAddress.getHostAddress();
                }
            }
        }
    } catch (SocketException e) {
        Log.i(TAG, e.toString());
    }
    return null;
}
 
Example 9
Source File: LocalUtil.java    From EserKnife with Apache License 2.0 6 votes vote down vote up
/**
 * 获取本机ip地址
 * 此方法为重量级的方法,不要频繁调用
 * <br/> Created on 2013-11-21 下午2:36:27
 * @author  李洪波([email protected])
 * @since 3.2
 * @return
 */
public static String getLocalIp(){
    try{
        //根据网卡取本机配置的IP
        Enumeration<NetworkInterface> netInterfaces=NetworkInterface.getNetworkInterfaces();
        String ip = null;
        a: while(netInterfaces.hasMoreElements()){
            NetworkInterface ni=netInterfaces.nextElement();
            Enumeration<InetAddress> ips = ni.getInetAddresses();
            while (ips.hasMoreElements()) {
                InetAddress ipObj = ips.nextElement();
                if (ipObj.isSiteLocalAddress()) {
                    ip =  ipObj.getHostAddress();
                    break a;
                }
            }
        }
        return ip;
    }catch (Exception e){
        LOGGER.error("", e);
        return null;
    }
}
 
Example 10
Source File: IpUtil.java    From jeecg with Apache License 2.0 6 votes vote down vote up
/**
* 获取本地IP列表(针对多网卡情况)
*
* @return
*/
public static List<String> getLocalIPList() {
      List<String> ipList = new ArrayList<String>();
      try {
          Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
          NetworkInterface networkInterface;
          Enumeration<InetAddress> inetAddresses;
          InetAddress inetAddress;
          String ip;
          while (networkInterfaces.hasMoreElements()) {
              networkInterface = networkInterfaces.nextElement();
              inetAddresses = networkInterface.getInetAddresses();
              while (inetAddresses.hasMoreElements()) {
                  inetAddress = inetAddresses.nextElement();
                  if (inetAddress != null && inetAddress instanceof Inet4Address) { // IPV4
                      ip = inetAddress.getHostAddress();
                      ipList.add(ip);
                      //System.out.println("获取本机IP:"+ip);
                  }
              }
          }
      } catch (SocketException e) {
          e.printStackTrace();
      }
      return ipList;
}
 
Example 11
Source File: CommandServer.java    From IBC with GNU General Public License v3.0 6 votes vote down vote up
private List<String> getAddressList() {
    List<String> addressList = new ArrayList<>(); 
    try {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface iface = interfaces.nextElement();

            Enumeration<InetAddress> addresses = iface.getInetAddresses();
            while(addresses.hasMoreElements()) {
                InetAddress address = addresses.nextElement();
                addressList.add(address.getHostAddress());
            }
        }
    } catch (SocketException e) {
        Utils.logToConsole("SocketException occurred while enumerating network interfaces");
    }
    return addressList;
}
 
Example 12
Source File: DeviceInfoUtil.java    From SoloPi with Apache License 2.0 6 votes vote down vote up
private static InetAddress getLocalInetAddress() {
    InetAddress ip = null;
    try {
        Enumeration<NetworkInterface> en_netInterface = NetworkInterface.getNetworkInterfaces();
        while (en_netInterface.hasMoreElements()) {
            NetworkInterface ni = en_netInterface.nextElement();
            Enumeration<InetAddress> en_ip = ni.getInetAddresses();
            while (en_ip.hasMoreElements()) {
                ip = en_ip.nextElement();
                if (!ip.isLoopbackAddress() && !ip.getHostAddress().contains(":"))
                    break;
                else
                    ip = null;
            }
            if (ip != null) {
                break;
            }
        }
    } catch (SocketException e) {
        LogUtil.e(TAG, "getLocalInetAddress exception: " + e.getMessage(), e);
    }
    return ip;
}
 
Example 13
Source File: LocalServerParser.java    From movienow with GNU General Public License v3.0 6 votes vote down vote up
private static String getLocalIPAddress() {
    try {
        for (Enumeration<NetworkInterface> mEnumeration = NetworkInterface
                .getNetworkInterfaces(); mEnumeration.hasMoreElements(); ) {
            NetworkInterface intf = mEnumeration.nextElement();
            for (Enumeration<InetAddress> enumIPAddr = intf
                    .getInetAddresses(); enumIPAddr.hasMoreElements(); ) {
                InetAddress inetAddress = enumIPAddr.nextElement();
                // 如果不是回环地址
                if (!inetAddress.isLoopbackAddress()) {
                    // 直接返回本地IP地址
                    return inetAddress.getHostAddress();
                }
            }
        }
    } catch (SocketException ex) {
        System.err.print("error");
    }
    return "127.0.0.1";
}
 
Example 14
Source File: UpnpUtil.java    From DroidDLNA with GNU General Public License v3.0 5 votes vote down vote up
public static boolean isLocalIpAddress(String checkip) {

        boolean ret = false;
        if (checkip != null) {
            try {
                for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                        .hasMoreElements();) {
                    NetworkInterface intf = en.nextElement();
                    for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
                            .hasMoreElements();) {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        if (!inetAddress.isLoopbackAddress()) {
                            String ip = inetAddress.getHostAddress().toString();

                            if (ip == null) {
                                continue;
                            }
                            if (checkip.equals(ip)) {
                                return true;
                            }
                        }
                    }
                }
            } catch (SocketException ex) {
                ex.printStackTrace();
            }
        }

        return ret;
    }
 
Example 15
Source File: SetGetNetworkInterfaceTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static void printNetIfDetails(NetworkInterface ni)
        throws SocketException {
    System.out.println("Name " + ni.getName() + " index " + ni.getIndex());
    Enumeration<InetAddress> en = ni.getInetAddresses();
    while (en.hasMoreElements()) {
        System.out.println(" InetAdress: " + en.nextElement());
    }
    System.out.println("HardwareAddress: " + createMacAddrString(ni));
    System.out.println("loopback: " + ni.isLoopback() + "; pointToPoint: "
            + ni.isPointToPoint() + "; virtual: " + ni.isVirtual()
            + "; MTU: " + ni.getMTU());
}
 
Example 16
Source File: AlipayUtils.java    From alipay-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * 获取本机的网络IP
 */
public static String getLocalNetWorkIp() {
    if (localIp != null) {
        return localIp;
    }
    try {
        Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
        InetAddress ip = null;
        while (netInterfaces.hasMoreElements()) {// 遍历所有的网卡
            NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
            if (ni.isLoopback() || ni.isVirtual()) {// 如果是回环和虚拟网络地址的话继续
                continue;
            }
            Enumeration<InetAddress> addresss = ni.getInetAddresses();
            while (addresss.hasMoreElements()) {
                InetAddress address = addresss.nextElement();
                if (address instanceof Inet4Address) {// 这里暂时只获取ipv4地址
                    ip = address;
                    break;
                }
            }
            if (ip != null) {
                break;
            }
        }
        if (ip != null) {
            localIp = ip.getHostAddress();
        } else {
            localIp = "127.0.0.1";
        }
    } catch (Exception e) {
        localIp = "127.0.0.1";
    }
    return localIp;
}
 
Example 17
Source File: RegisterActivity.java    From stynico with MIT License 5 votes vote down vote up
public static String getHostIP() {

        String hostIp = null;
        try {
            Enumeration nis = NetworkInterface.getNetworkInterfaces();
            InetAddress ia = null;
            while (nis.hasMoreElements()) {
                NetworkInterface ni = (NetworkInterface) nis.nextElement();
                Enumeration<InetAddress> ias = ni.getInetAddresses();
                while (ias.hasMoreElements()) {
                    ia = ias.nextElement();
                    if (ia instanceof Inet6Address) {
                        continue;// skip ipv6
                    }
                    String ip = ia.getHostAddress();
                    if (!"127.0.0.1".equals(ip)) {
                        hostIp = ia.getHostAddress();
                        break;
                    }
                }
            }
        } catch (SocketException e) {
            // Log.i("yao", "SocketException");
            e.printStackTrace();
        }
        return hostIp;

    }
 
Example 18
Source File: Controller.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Returns interface MAC by index.
 *
 * @param interfaceIndex interface index
 * @return interface IP by index
 */
private String getInterfaceMask(int interfaceIndex) {
    String subnetMask = null;
    try {
        Ip4Address ipAddress = getInterfaceIp(interfaceIndex);
        NetworkInterface networkInterface = NetworkInterface.getByInetAddress(
                InetAddress.getByName(ipAddress.toString()));
        Enumeration ipAddresses = networkInterface.getInetAddresses();
        int index = 0;
        while (ipAddresses.hasMoreElements()) {
            InetAddress address = (InetAddress) ipAddresses.nextElement();
            if (!address.isLinkLocalAddress()) {
                break;
            }
            index++;
        }
        int prfLen = networkInterface.getInterfaceAddresses().get(index).getNetworkPrefixLength();
        int shft = 0xffffffff << (32 - prfLen);
        int oct1 = ((byte) ((shft & 0xff000000) >> 24)) & 0xff;
        int oct2 = ((byte) ((shft & 0x00ff0000) >> 16)) & 0xff;
        int oct3 = ((byte) ((shft & 0x0000ff00) >> 8)) & 0xff;
        int oct4 = ((byte) (shft & 0x000000ff)) & 0xff;
        subnetMask = oct1 + "." + oct2 + "." + oct3 + "." + oct4;
    } catch (Exception e) {
        log.debug("Error while getting Interface network mask by index");
        return subnetMask;
    }
    return subnetMask;
}
 
Example 19
Source File: ZooKeeperReplicationConfig.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
private static int findServerId(Map<Integer, ZooKeeperAddress> servers, int currentServerId,
                                NetworkInterface iface) {
    for (final Enumeration<InetAddress> ea = iface.getInetAddresses(); ea.hasMoreElements();) {
        currentServerId = findServerId(servers, currentServerId, ea.nextElement());
    }
    return currentServerId;
}
 
Example 20
Source File: RemotingUtil.java    From rocketmq-read with Apache License 2.0 4 votes vote down vote up
/**
 * 获取本地的网卡的接口地址。
 * @return ;
 */
public static String getLocalAddress() {
    try {
        // Traversal Network interface to get the first non-loopback and non-private address
        Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
        ArrayList<String> ipv4Result = new ArrayList<String>();
        ArrayList<String> ipv6Result = new ArrayList<String>();
        while (enumeration.hasMoreElements()) {
            final NetworkInterface networkInterface = enumeration.nextElement();
            final Enumeration<InetAddress> en = networkInterface.getInetAddresses();
            while (en.hasMoreElements()) {
                final InetAddress address = en.nextElement();
                //过滤掉回环地址
                if (!address.isLoopbackAddress()) {
                    if (address instanceof Inet6Address) {
                        ipv6Result.add(normalizeHostAddress(address));
                    } else {
                        ipv4Result.add(normalizeHostAddress(address));
                    }
                }
            }
        }

        // prefer ipv4
        if (!ipv4Result.isEmpty()) {
            for (String ip : ipv4Result) {
                //过滤掉127.0.x和192。168
                if (ip.startsWith("127.0") || ip.startsWith("192.168")) {
                    continue;
                }

                return ip;
            }

            return ipv4Result.get(ipv4Result.size() - 1);
        } else if (!ipv6Result.isEmpty()) {
            return ipv6Result.get(0);
        }
        //If failed to find,fall back to localhost
        //都失败就返回localhost
        final InetAddress localHost = InetAddress.getLocalHost();
        return normalizeHostAddress(localHost);
    } catch (Exception e) {
        log.error("Failed to obtain local address", e);
    }

    return null;
}