Search in sources :

Example 81 with NetworkInterface

use of java.net.NetworkInterface in project AndroidUtilCode by Blankj.

the class NetworkUtils method getIPAddress.

/**
     * 获取IP地址
     * <p>需添加权限 {@code <uses-permission android:name="android.permission.INTERNET"/>}</p>
     *
     * @param useIPv4 是否用IPv4
     * @return IP地址
     */
public static String getIPAddress(boolean useIPv4) {
    try {
        for (Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces(); nis.hasMoreElements(); ) {
            NetworkInterface ni = nis.nextElement();
            // 防止小米手机返回10.0.2.15
            if (!ni.isUp())
                continue;
            for (Enumeration<InetAddress> addresses = ni.getInetAddresses(); addresses.hasMoreElements(); ) {
                InetAddress inetAddress = addresses.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    String hostAddress = inetAddress.getHostAddress();
                    boolean isIPv4 = hostAddress.indexOf(':') < 0;
                    if (useIPv4) {
                        if (isIPv4)
                            return hostAddress;
                    } else {
                        if (!isIPv4) {
                            int index = hostAddress.indexOf('%');
                            return index < 0 ? hostAddress.toUpperCase() : hostAddress.substring(0, index).toUpperCase();
                        }
                    }
                }
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
    }
    return null;
}
Also used : SocketException(java.net.SocketException) NetworkInterface(java.net.NetworkInterface) InetAddress(java.net.InetAddress)

Example 82 with NetworkInterface

use of java.net.NetworkInterface in project CloudStack-archive by CloudStack-extras.

the class NetUtils method getAllLocalInetAddresses.

public static InetAddress[] getAllLocalInetAddresses() {
    List<InetAddress> addrList = new ArrayList<InetAddress>();
    try {
        for (NetworkInterface ifc : IteratorUtil.enumerationAsIterable(NetworkInterface.getNetworkInterfaces())) {
            if (ifc.isUp() && !ifc.isVirtual()) {
                for (InetAddress addr : IteratorUtil.enumerationAsIterable(ifc.getInetAddresses())) {
                    addrList.add(addr);
                }
            }
        }
    } catch (SocketException e) {
        s_logger.warn("SocketException in getAllLocalInetAddresses().", e);
    }
    InetAddress[] addrs = new InetAddress[addrList.size()];
    if (addrList.size() > 0) {
        System.arraycopy(addrList.toArray(), 0, addrs, 0, addrList.size());
    }
    return addrs;
}
Also used : SocketException(java.net.SocketException) ArrayList(java.util.ArrayList) NetworkInterface(java.net.NetworkInterface) InetAddress(java.net.InetAddress)

Example 83 with NetworkInterface

use of java.net.NetworkInterface in project CloudStack-archive by CloudStack-extras.

the class NetUtils method getLocalCidrs.

public static String[] getLocalCidrs() {
    String defaultHostIp = getDefaultHostIp();
    List<String> cidrList = new ArrayList<String>();
    try {
        for (NetworkInterface ifc : IteratorUtil.enumerationAsIterable(NetworkInterface.getNetworkInterfaces())) {
            if (ifc.isUp() && !ifc.isVirtual() && !ifc.isLoopback()) {
                for (InterfaceAddress address : ifc.getInterfaceAddresses()) {
                    InetAddress addr = address.getAddress();
                    int prefixLength = address.getNetworkPrefixLength();
                    if (prefixLength < 32 && prefixLength > 0) {
                        String ip = ipFromInetAddress(addr);
                        if (ip.equalsIgnoreCase(defaultHostIp))
                            cidrList.add(ipAndNetMaskToCidr(ip, getCidrNetmask(prefixLength)));
                    }
                }
            }
        }
    } catch (SocketException e) {
        s_logger.warn("UnknownHostException in getLocalCidrs().", e);
    }
    return cidrList.toArray(new String[0]);
}
Also used : SocketException(java.net.SocketException) InterfaceAddress(java.net.InterfaceAddress) ArrayList(java.util.ArrayList) NetworkInterface(java.net.NetworkInterface) InetAddress(java.net.InetAddress)

Example 84 with NetworkInterface

use of java.net.NetworkInterface in project alluxio by Alluxio.

the class NetworkAddressUtils method getLocalIpAddress.

/**
   * Gets a local IP address for the host this JVM is running on.
   *
   * @param timeoutMs Timeout in milliseconds to use for checking that a possible local IP is
   *        reachable
   * @return the local ip address, which is not a loopback address and is reachable
   */
public static synchronized String getLocalIpAddress(int timeoutMs) {
    if (sLocalIP != null) {
        return sLocalIP;
    }
    try {
        InetAddress address = InetAddress.getLocalHost();
        LOG.debug("address: {} isLoopbackAddress: {}, with host {} {}", address, address.isLoopbackAddress(), address.getHostAddress(), address.getHostName());
        // address e.g. a broadcast address
        if (!isValidAddress(address, timeoutMs)) {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            // possible.
            if (!WINDOWS) {
                List<NetworkInterface> netIFs = Collections.list(networkInterfaces);
                Collections.reverse(netIFs);
                networkInterfaces = Collections.enumeration(netIFs);
            }
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface ni = networkInterfaces.nextElement();
                Enumeration<InetAddress> addresses = ni.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    address = addresses.nextElement();
                    // Address must not be link local or loopback. And it must be reachable
                    if (isValidAddress(address, timeoutMs)) {
                        sLocalIP = address.getHostAddress();
                        return sLocalIP;
                    }
                }
            }
            LOG.warn("Your hostname, " + InetAddress.getLocalHost().getHostName() + " resolves to" + " a loopback/non-reachable address: " + address.getHostAddress() + ", but we couldn't find any external IP address!");
        }
        sLocalIP = address.getHostAddress();
        return sLocalIP;
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}
Also used : NetworkInterface(java.net.NetworkInterface) IOException(java.io.IOException) InetAddress(java.net.InetAddress)

Example 85 with NetworkInterface

use of java.net.NetworkInterface in project wifikeyboard by IvanVolosyuk.

the class WiFiKeyboard method getNetworkAddresses.

public static ArrayList<String> getNetworkAddresses() {
    ArrayList<String> addrs = new ArrayList<String>();
    try {
        Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
        while (ifaces.hasMoreElements()) {
            NetworkInterface iface = ifaces.nextElement();
            if ("lo".equals(iface.getName()))
                continue;
            Enumeration<InetAddress> addresses = iface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress addr = addresses.nextElement();
                addrs.add(addr.getHostAddress());
            }
        }
    } catch (SocketException e) {
        Debug.d("failed to get network interfaces");
    }
    return addrs;
}
Also used : SocketException(java.net.SocketException) ArrayList(java.util.ArrayList) NetworkInterface(java.net.NetworkInterface) InetAddress(java.net.InetAddress)

Aggregations

NetworkInterface (java.net.NetworkInterface)225 InetAddress (java.net.InetAddress)178 SocketException (java.net.SocketException)112 ArrayList (java.util.ArrayList)42 Inet4Address (java.net.Inet4Address)39 UnknownHostException (java.net.UnknownHostException)36 InterfaceAddress (java.net.InterfaceAddress)32 Inet6Address (java.net.Inet6Address)29 IOException (java.io.IOException)25 Enumeration (java.util.Enumeration)9 InetSocketAddress (java.net.InetSocketAddress)7 HashSet (java.util.HashSet)7 LinkedHashSet (java.util.LinkedHashSet)7 Command (com.android.server.NativeDaemonConnector.Command)6 Test (org.junit.Test)6 DatagramSocket (java.net.DatagramSocket)5 File (java.io.File)4 MulticastSocket (java.net.MulticastSocket)4 List (java.util.List)4 SharedPreferences (android.content.SharedPreferences)3