Search in sources :

Example 76 with NetworkInterface

use of java.net.NetworkInterface in project android_frameworks_base by ResurrectionRemix.

the class WifiDisplayController method getInterfaceAddress.

private static Inet4Address getInterfaceAddress(WifiP2pGroup info) {
    NetworkInterface iface;
    try {
        iface = NetworkInterface.getByName(info.getInterface());
    } catch (SocketException ex) {
        Slog.w(TAG, "Could not obtain address of network interface " + info.getInterface(), ex);
        return null;
    }
    Enumeration<InetAddress> addrs = iface.getInetAddresses();
    while (addrs.hasMoreElements()) {
        InetAddress addr = addrs.nextElement();
        if (addr instanceof Inet4Address) {
            return (Inet4Address) addr;
        }
    }
    Slog.w(TAG, "Could not obtain address of network interface " + info.getInterface() + " because it had no IPv4 addresses.");
    return null;
}
Also used : SocketException(java.net.SocketException) Inet4Address(java.net.Inet4Address) NetworkInterface(java.net.NetworkInterface) InetAddress(java.net.InetAddress)

Example 77 with NetworkInterface

use of java.net.NetworkInterface in project java-chassis by ServiceComb.

the class SSLManagerTest method testSSLManagerServerAndClient.

@Test
public void testSSLManagerServerAndClient(@Mocked final NetworkInterface nif) throws Exception {
    final InetAddress ia = Inet4Address.getByName("10.57.65.225");
    final Enumeration<NetworkInterface> interfaces = new Enumeration<NetworkInterface>() {

        int count = 1;

        int cur = 0;

        @Override
        public boolean hasMoreElements() {
            if (cur < count) {
                cur++;
                return true;
            }
            return false;
        }

        @Override
        public NetworkInterface nextElement() {
            return nif;
        }
    };
    final Enumeration<InetAddress> ias = new Enumeration<InetAddress>() {

        int count = 1;

        int cur = 0;

        @Override
        public boolean hasMoreElements() {
            if (cur < count) {
                cur++;
                return true;
            }
            return false;
        }

        @Override
        public InetAddress nextElement() {
            return ia;
        }
    };
    new Expectations() {

        @Mocked
        NetworkInterface nif;

        {
            NetworkInterface.getNetworkInterfaces();
            result = interfaces;
        }
    };
    new Expectations() {

        {
            nif.getInetAddresses();
            result = ias;
            ia.getHostAddress();
            result = "10.57.65.225";
        }
    };
    SSLOption option = SSLOption.build(DIR + "/server.ssl.properties");
    SSLCustom custom = new SSLCustom() {

        @Override
        public String getFullPath(String filename) {
            return DIR + "/ssl/" + filename;
        }

        @Override
        public char[] decode(char[] encrypted) {
            return encrypted;
        }
    };
    final SSLServerSocket serverSocket = SSLManager.createSSLServerSocket(option, custom);
    serverSocket.bind(new InetSocketAddress("127.0.0.1", 8886));
    String[] protos = serverSocket.getEnabledCipherSuites();
    String[] protosExpected = "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,TLS_DHE_DSS_WITH_AES_128_CBC_SHA256,TLS_RSA_WITH_AES_128_CBC_SHA256,TLS_DHE_RSA_WITH_AES_128_CBC_SHA,TLS_DHE_DSS_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_128_CBC_SHA".split(",");
    Assert.assertArrayEquals(protos, protosExpected);
    String[] ciphers = serverSocket.getEnabledCipherSuites();
    String[] ciphersExpected = "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,TLS_DHE_DSS_WITH_AES_128_CBC_SHA256,TLS_RSA_WITH_AES_128_CBC_SHA256,TLS_DHE_RSA_WITH_AES_128_CBC_SHA,TLS_DHE_DSS_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_128_CBC_SHA".split(",");
    Assert.assertArrayEquals(ciphers, ciphersExpected);
    Assert.assertEquals(serverSocket.getNeedClientAuth(), true);
    SSLOption clientoption = SSLOption.build(DIR + "/client.ssl.properties");
    SSLSocket clientsocket = SSLManager.createSSLSocket(clientoption, custom);
    String[] clientprotos = clientsocket.getEnabledCipherSuites();
    String[] clientprotosExpected = "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,TLS_DHE_DSS_WITH_AES_128_CBC_SHA256,TLS_RSA_WITH_AES_128_CBC_SHA256,TLS_DHE_RSA_WITH_AES_128_CBC_SHA,TLS_DHE_DSS_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_128_CBC_SHA".split(",");
    Assert.assertArrayEquals(clientprotos, clientprotosExpected);
    String[] clientciphers = clientsocket.getEnabledCipherSuites();
    String[] clientciphersExpected = "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,TLS_DHE_DSS_WITH_AES_128_CBC_SHA256,TLS_RSA_WITH_AES_128_CBC_SHA256,TLS_DHE_RSA_WITH_AES_128_CBC_SHA,TLS_DHE_DSS_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_128_CBC_SHA".split(",");
    Assert.assertArrayEquals(clientciphers, clientciphersExpected);
    Assert.assertEquals(clientsocket.getNeedClientAuth(), false);
    boolean validAssert = true;
    try {
        clientsocket.connect(new InetSocketAddress("127.0.0.1", 8886));
        new Thread() {

            public void run() {
                try {
                    SSLSocket s = (SSLSocket) serverSocket.accept();
                    s.addHandshakeCompletedListener(new HandshakeCompletedListener() {

                        @Override
                        public void handshakeCompleted(HandshakeCompletedEvent arg0) {
                        }
                    });
                    s.getOutputStream().write(new byte[] { 0, 1 });
                } catch (IOException e) {
                    e.printStackTrace();
                    // this should not happen, do a false assert
                    Assert.assertEquals(false, true);
                }
            }
        }.start();
        clientsocket.startHandshake();
        clientsocket.close();
        serverSocket.close();
    // socked successfully opened and closed
    } catch (Exception e) {
        e.printStackTrace();
        validAssert = false;
    }
    Assert.assertTrue(validAssert);
}
Also used : Expectations(mockit.Expectations) Enumeration(java.util.Enumeration) InetSocketAddress(java.net.InetSocketAddress) SSLSocket(javax.net.ssl.SSLSocket) NetworkInterface(java.net.NetworkInterface) IOException(java.io.IOException) SSLServerSocket(javax.net.ssl.SSLServerSocket) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) UnknownHostException(java.net.UnknownHostException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) HandshakeCompletedListener(javax.net.ssl.HandshakeCompletedListener) HandshakeCompletedEvent(javax.net.ssl.HandshakeCompletedEvent) InetAddress(java.net.InetAddress) Test(org.junit.Test)

Example 78 with NetworkInterface

use of java.net.NetworkInterface in project java-chassis by ServiceComb.

the class TrustManagerExt method checkCNHost.

// ? : learn java default / apache CN check
private void checkCNHost(X509Certificate[] chain, String ip) throws CertificateException {
    if (option.isCheckCNHost()) {
        X509Certificate owner = CertificateUtil.findOwner(chain);
        Set<String> cns = CertificateUtil.getCN(owner);
        String ipTmp = ip == null ? custom.getHost() : ip;
        // 从本机来的请求, 只要CN与本机的任何一个IP地址匹配即可
        if ("127.0.0.1".equals(ipTmp)) {
            try {
                Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
                if (interfaces != null) {
                    while (interfaces.hasMoreElements()) {
                        NetworkInterface nif = interfaces.nextElement();
                        Enumeration<InetAddress> ias = nif.getInetAddresses();
                        while (ias.hasMoreElements()) {
                            InetAddress ia = ias.nextElement();
                            String local = ia.getHostAddress();
                            if (cnValid(cns, local)) {
                                return;
                            }
                        }
                    }
                }
            } catch (SocketException e) {
                throw new CertificateException("Get local adrress fail.");
            }
        } else if (cnValid(cns, ipTmp)) {
            return;
        }
        LOG.error("CN does not match IP: e=" + cns.toString() + ",t=" + ip);
        throw new CertificateException("CN does not match IP: e=" + cns.toString() + ",t=" + ip);
    }
}
Also used : SocketException(java.net.SocketException) NetworkInterface(java.net.NetworkInterface) CertificateException(java.security.cert.CertificateException) InetAddress(java.net.InetAddress) X509Certificate(java.security.cert.X509Certificate)

Example 79 with NetworkInterface

use of java.net.NetworkInterface in project java-chassis by ServiceComb.

the class NetUtils method doGetIpv4AddressFromNetworkInterface.

private static void doGetIpv4AddressFromNetworkInterface() throws SocketException {
    Enumeration<NetworkInterface> iterNetwork = NetworkInterface.getNetworkInterfaces();
    while (iterNetwork.hasMoreElements()) {
        NetworkInterface network = iterNetwork.nextElement();
        if (!network.isUp() || network.isLoopback() || network.isVirtual()) {
            continue;
        }
        Enumeration<InetAddress> iterAddress = network.getInetAddresses();
        while (iterAddress.hasMoreElements()) {
            InetAddress address = iterAddress.nextElement();
            if (address.isAnyLocalAddress() || address.isLoopbackAddress() || address.isMulticastAddress() || Inet6Address.class.isInstance(address)) {
                continue;
            }
            if (Inet4Address.class.isInstance(address)) {
                String host = address.getHostName();
                if (host == null) {
                    host = network.getName();
                }
                hostName = host;
                hostAddress = address.getHostAddress();
                LOGGER.info("add hostName:" + host + ",hostAddress:" + address.getHostAddress());
                allHostAddresses.put(address.getHostName(), address.getHostAddress());
            }
        }
    }
    return;
}
Also used : NetworkInterface(java.net.NetworkInterface) Inet6Address(java.net.Inet6Address) InetAddress(java.net.InetAddress)

Example 80 with NetworkInterface

use of java.net.NetworkInterface in project voltdb by VoltDB.

the class RealVoltDB method collectLocalNetworkMetadata.

void collectLocalNetworkMetadata() {
    boolean threw = false;
    JSONStringer stringer = new JSONStringer();
    try {
        stringer.object();
        stringer.key("interfaces").array();
        if (m_config.m_externalInterface.equals("")) {
            LinkedList<NetworkInterface> interfaces = new LinkedList<>();
            try {
                Enumeration<NetworkInterface> intfEnum = NetworkInterface.getNetworkInterfaces();
                while (intfEnum.hasMoreElements()) {
                    NetworkInterface intf = intfEnum.nextElement();
                    if (intf.isLoopback() || !intf.isUp()) {
                        continue;
                    }
                    interfaces.offer(intf);
                }
            } catch (SocketException e) {
                throw new RuntimeException(e);
            }
            if (interfaces.isEmpty()) {
                stringer.value("localhost");
            } else {
                boolean addedIp = false;
                while (!interfaces.isEmpty()) {
                    NetworkInterface intf = interfaces.poll();
                    Enumeration<InetAddress> inetAddrs = intf.getInetAddresses();
                    Inet6Address inet6addr = null;
                    Inet4Address inet4addr = null;
                    while (inetAddrs.hasMoreElements()) {
                        InetAddress addr = inetAddrs.nextElement();
                        if (addr instanceof Inet6Address) {
                            inet6addr = (Inet6Address) addr;
                            if (inet6addr.isLinkLocalAddress()) {
                                inet6addr = null;
                            }
                        } else if (addr instanceof Inet4Address) {
                            inet4addr = (Inet4Address) addr;
                        }
                    }
                    if (inet4addr != null) {
                        stringer.value(inet4addr.getHostAddress());
                        addedIp = true;
                    }
                    if (inet6addr != null) {
                        stringer.value(inet6addr.getHostAddress());
                        addedIp = true;
                    }
                }
                if (!addedIp) {
                    stringer.value("localhost");
                }
            }
        } else {
            stringer.value(m_config.m_externalInterface);
        }
    } catch (Exception e) {
        threw = true;
        hostLog.warn("Error while collecting data about local network interfaces", e);
    }
    try {
        if (threw) {
            stringer = new JSONStringer();
            stringer.object();
            stringer.key("interfaces").array();
            stringer.value("localhost");
            stringer.endArray();
        } else {
            stringer.endArray();
        }
        stringer.keySymbolValuePair("clientPort", m_config.m_port);
        stringer.keySymbolValuePair("clientInterface", m_config.m_clientInterface);
        stringer.keySymbolValuePair("adminPort", m_config.m_adminPort);
        stringer.keySymbolValuePair("adminInterface", m_config.m_adminInterface);
        stringer.keySymbolValuePair("httpPort", m_config.m_httpPort);
        stringer.keySymbolValuePair("httpInterface", m_config.m_httpPortInterface);
        stringer.keySymbolValuePair("internalPort", m_config.m_internalPort);
        stringer.keySymbolValuePair("internalInterface", m_config.m_internalInterface);
        String[] zkInterface = m_config.m_zkInterface.split(":");
        stringer.keySymbolValuePair("zkPort", zkInterface[1]);
        stringer.keySymbolValuePair("zkInterface", zkInterface[0]);
        stringer.keySymbolValuePair("drPort", VoltDB.getReplicationPort(m_catalogContext.cluster.getDrproducerport()));
        stringer.keySymbolValuePair("drInterface", VoltDB.getDefaultReplicationInterface());
        stringer.keySymbolValuePair("publicInterface", m_config.m_publicInterface);
        stringer.endObject();
        JSONObject obj = new JSONObject(stringer.toString());
        // possibly atomic swap from null to realz
        m_localMetadata = obj.toString(4);
        hostLog.debug("System Metadata is: " + m_localMetadata);
    } catch (Exception e) {
        hostLog.warn("Failed to collect data about lcoal network interfaces", e);
    }
}
Also used : SocketException(java.net.SocketException) Inet4Address(java.net.Inet4Address) NetworkInterface(java.net.NetworkInterface) Inet6Address(java.net.Inet6Address) LinkedList(java.util.LinkedList) SocketException(java.net.SocketException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) JSONException(org.json_voltpatches.JSONException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) KeeperException(org.apache.zookeeper_voltpatches.KeeperException) SettingsException(org.voltdb.settings.SettingsException) JSONObject(org.json_voltpatches.JSONObject) JSONStringer(org.json_voltpatches.JSONStringer) 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