Search in sources :

Example 26 with NetworkInterface

use of java.net.NetworkInterface in project Smack by igniterealtime.

the class ICEResolver method resolve.

/**
     * Resolve the IP and obtain a valid transport method.
     * @throws SmackException 
     * @throws InterruptedException 
     */
@Override
public synchronized void resolve(JingleSession session) throws XMPPException, SmackException, InterruptedException {
    this.setResolveInit();
    for (TransportCandidate candidate : this.getCandidatesList()) {
        if (candidate instanceof ICECandidate) {
            ICECandidate iceCandidate = (ICECandidate) candidate;
            iceCandidate.removeCandidateEcho();
        }
    }
    this.clear();
    // Create a transport candidate for each ICE negotiator candidate we have.
    ICENegociator iceNegociator = negociatorsMap.get(server);
    for (Candidate candidate : iceNegociator.getSortedCandidates()) try {
        Candidate.CandidateType type = candidate.getCandidateType();
        ICECandidate.Type iceType = ICECandidate.Type.local;
        if (type.equals(Candidate.CandidateType.ServerReflexive))
            iceType = ICECandidate.Type.srflx;
        else if (type.equals(Candidate.CandidateType.PeerReflexive))
            iceType = ICECandidate.Type.prflx;
        else if (type.equals(Candidate.CandidateType.Relayed))
            iceType = ICECandidate.Type.relay;
        else
            iceType = ICECandidate.Type.host;
        // JBW/GW - 17JUL08: Figure out the zero-based NIC number for this candidate.
        short nicNum = 0;
        try {
            Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();
            short i = 0;
            NetworkInterface nic = NetworkInterface.getByInetAddress(candidate.getAddress().getInetAddress());
            while (nics.hasMoreElements()) {
                NetworkInterface checkNIC = nics.nextElement();
                if (checkNIC.equals(nic)) {
                    nicNum = i;
                    break;
                }
                i++;
            }
        } catch (SocketException e1) {
            LOGGER.log(Level.WARNING, "exeption", e1);
        }
        TransportCandidate transportCandidate = new ICECandidate(candidate.getAddress().getInetAddress().getHostAddress(), 1, nicNum, String.valueOf(Math.abs(random.nextLong())), candidate.getPort(), "1", candidate.getPriority(), iceType);
        transportCandidate.setLocalIp(candidate.getBase().getAddress().getInetAddress().getHostAddress());
        transportCandidate.setPort(getFreePort());
        try {
            transportCandidate.addCandidateEcho(session);
        } catch (SocketException e) {
            LOGGER.log(Level.WARNING, "exception", e);
        }
        this.addCandidate(transportCandidate);
        LOGGER.fine("Candidate addr: " + candidate.getAddress().getInetAddress() + "|" + candidate.getBase().getAddress().getInetAddress() + " Priority:" + candidate.getPriority());
    } catch (UtilityException e) {
        LOGGER.log(Level.WARNING, "exception", e);
    } catch (UnknownHostException e) {
        LOGGER.log(Level.WARNING, "exception", e);
    }
    if (RTPBridge.serviceAvailable(connection)) {
        //            try {
        String localIp;
        int network;
        // JBW/GW - 17JUL08: ICENegotiator.getPublicCandidate() always returned null in JSTUN 1.7.0, and now the API doesn't exist in JSTUN 1.7.1
        //                if (iceNegociator.getPublicCandidate() != null) {
        //                    localIp = iceNegociator.getPublicCandidate().getBase().getAddress().getInetAddress().getHostAddress();
        //                    network = iceNegociator.getPublicCandidate().getNetwork();
        //                }
        //                else {
        {
            localIp = BridgedResolver.getLocalHost();
            network = 0;
        }
        sid = Math.abs(random.nextLong());
        RTPBridge rtpBridge = RTPBridge.getRTPBridge(connection, String.valueOf(sid));
        TransportCandidate localCandidate = new ICECandidate(rtpBridge.getIp(), 1, network, String.valueOf(Math.abs(random.nextLong())), rtpBridge.getPortA(), "1", 0, ICECandidate.Type.relay);
        localCandidate.setLocalIp(localIp);
        TransportCandidate remoteCandidate = new ICECandidate(rtpBridge.getIp(), 1, network, String.valueOf(Math.abs(random.nextLong())), rtpBridge.getPortB(), "1", 0, ICECandidate.Type.relay);
        remoteCandidate.setLocalIp(localIp);
        localCandidate.setSymmetric(remoteCandidate);
        remoteCandidate.setSymmetric(localCandidate);
        localCandidate.setPassword(rtpBridge.getPass());
        remoteCandidate.setPassword(rtpBridge.getPass());
        localCandidate.setSessionId(rtpBridge.getSid());
        remoteCandidate.setSessionId(rtpBridge.getSid());
        localCandidate.setConnection(this.connection);
        remoteCandidate.setConnection(this.connection);
        addCandidate(localCandidate);
        //          if (iceNegociator.getPublicCandidate() == null) {
        if (true) {
            String publicIp = RTPBridge.getPublicIP(connection);
            if (publicIp != null && !publicIp.equals("")) {
                Enumeration<NetworkInterface> ifaces = null;
                try {
                    ifaces = NetworkInterface.getNetworkInterfaces();
                } catch (SocketException e) {
                    LOGGER.log(Level.WARNING, "exception", e);
                }
                // If detect this address in local machine, don't use it.
                boolean found = false;
                while (ifaces.hasMoreElements() && !false) {
                    NetworkInterface iface = ifaces.nextElement();
                    Enumeration<InetAddress> iaddresses = iface.getInetAddresses();
                    while (iaddresses.hasMoreElements()) {
                        InetAddress iaddress = iaddresses.nextElement();
                        if (iaddress.getHostAddress().indexOf(publicIp) > -1) {
                            found = true;
                            break;
                        }
                    }
                }
                if (!found) {
                    try {
                        TransportCandidate publicCandidate = new ICECandidate(publicIp, 1, 0, String.valueOf(Math.abs(random.nextLong())), getFreePort(), "1", 0, ICECandidate.Type.srflx);
                        publicCandidate.setLocalIp(InetAddress.getLocalHost().getHostAddress());
                        try {
                            publicCandidate.addCandidateEcho(session);
                        } catch (SocketException e) {
                            LOGGER.log(Level.WARNING, "exception", e);
                        }
                        addCandidate(publicCandidate);
                    } catch (UnknownHostException e) {
                        LOGGER.log(Level.WARNING, "exception", e);
                    }
                }
            }
        }
    }
    this.setResolveEnd();
}
Also used : Candidate(de.javawi.jstun.test.demo.ice.Candidate) SocketException(java.net.SocketException) Enumeration(java.util.Enumeration) UnknownHostException(java.net.UnknownHostException) NetworkInterface(java.net.NetworkInterface) UtilityException(de.javawi.jstun.util.UtilityException) ICENegociator(de.javawi.jstun.test.demo.ice.ICENegociator) InetAddress(java.net.InetAddress)

Example 27 with NetworkInterface

use of java.net.NetworkInterface in project Smack by igniterealtime.

the class RTPBridge method getPublicIP.

/**
     * Get Public Address from the Server.
     *
     * @param xmppConnection
     * @return public IP String or null if not found
     * @throws NotConnectedException 
     * @throws InterruptedException 
     */
@SuppressWarnings("deprecation")
public static String getPublicIP(XMPPConnection xmppConnection) throws NotConnectedException, InterruptedException {
    if (!xmppConnection.isConnected()) {
        return null;
    }
    RTPBridge rtpPacket = new RTPBridge(RTPBridge.BridgeAction.publicip);
    rtpPacket.setTo(RTPBridge.NAME + "." + xmppConnection.getXMPPServiceDomain());
    rtpPacket.setType(Type.set);
    // LOGGER.debug("Relayed to: " + candidate.getIp() + ":" + candidate.getPort());
    StanzaCollector collector = xmppConnection.createStanzaCollectorAndSend(rtpPacket);
    RTPBridge response = collector.nextResult();
    // Cancel the collector.
    collector.cancel();
    if (response == null)
        return null;
    if (response.getIp() == null || response.getIp().equals(""))
        return null;
    Enumeration<NetworkInterface> ifaces = null;
    try {
        ifaces = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
        LOGGER.log(Level.WARNING, "exception", e);
    }
    while (ifaces != null && ifaces.hasMoreElements()) {
        NetworkInterface iface = ifaces.nextElement();
        Enumeration<InetAddress> iaddresses = iface.getInetAddresses();
        while (iaddresses.hasMoreElements()) {
            InetAddress iaddress = iaddresses.nextElement();
            if (!iaddress.isLoopbackAddress())
                if (iaddress.getHostAddress().indexOf(response.getIp()) >= 0)
                    return null;
        }
    }
    return response.getIp();
}
Also used : SocketException(java.net.SocketException) NetworkInterface(java.net.NetworkInterface) StanzaCollector(org.jivesoftware.smack.StanzaCollector) InetAddress(java.net.InetAddress)

Example 28 with NetworkInterface

use of java.net.NetworkInterface in project Smack by igniterealtime.

the class STUNResolverTest method testICEPriority.

/**
     * Test priority generated by STUN lib
     *
     * @throws Exception
     */
public void testICEPriority() throws Exception {
    String first = "";
    for (int i = 0; i < 100; i++) {
        ICENegociator cc = new ICENegociator((short) 1);
        // gather candidates
        cc.gatherCandidateAddresses();
        // priorize candidates
        cc.prioritizeCandidates();
        for (Candidate candidate : cc.getSortedCandidates()) {
            short nicNum = 0;
            try {
                Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();
                short tempNic = 0;
                NetworkInterface nic = NetworkInterface.getByInetAddress(candidate.getAddress().getInetAddress());
                while (nics.hasMoreElements()) {
                    NetworkInterface checkNIC = nics.nextElement();
                    if (checkNIC.equals(nic)) {
                        nicNum = tempNic;
                        break;
                    }
                    i++;
                }
            } catch (SocketException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            try {
                TransportCandidate transportCandidate = new ICECandidate(candidate.getAddress().getInetAddress().getHostAddress(), 1, nicNum, "1", candidate.getPort(), "1", candidate.getPriority(), ICECandidate.Type.prflx);
                transportCandidate.setLocalIp(candidate.getBase().getAddress().getInetAddress().getHostAddress());
                System.out.println("C: " + candidate.getAddress().getInetAddress() + "|" + candidate.getBase().getAddress().getInetAddress() + " p:" + candidate.getPriority());
            } catch (UtilityException e) {
                LOGGER.log(Level.WARNING, "exception", e);
            } catch (UnknownHostException e) {
                LOGGER.log(Level.WARNING, "exception", e);
            }
        }
        Candidate candidate = cc.getSortedCandidates().get(0);
        String temp = "C: " + candidate.getAddress().getInetAddress() + "|" + candidate.getBase().getAddress().getInetAddress() + " p:" + candidate.getPriority();
        if (first.equals(""))
            first = temp;
        assertEquals(first, temp);
        first = temp;
    }
}
Also used : Candidate(de.javawi.jstun.test.demo.ice.Candidate) SocketException(java.net.SocketException) UnknownHostException(java.net.UnknownHostException) ICENegociator(de.javawi.jstun.test.demo.ice.ICENegociator) NetworkInterface(java.net.NetworkInterface) UtilityException(de.javawi.jstun.util.UtilityException)

Example 29 with NetworkInterface

use of java.net.NetworkInterface in project BeyondUPnP by kevinshine.

the class Utils method getIPAddress.

/**
     * Get IP address from first non-localhost interface
     *
     * @param useIPv4 true=return ipv4, false=return ipv6
     * @return address or empty string
     */
public static String getIPAddress(boolean useIPv4) {
    try {
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface intf : interfaces) {
            List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
            for (InetAddress addr : addrs) {
                if (!addr.isLoopbackAddress()) {
                    String sAddr = addr.getHostAddress().toUpperCase();
                    boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
                    if (useIPv4) {
                        if (isIPv4)
                            return sAddr;
                    } else {
                        if (!isIPv4) {
                            // drop ip6 port suffix
                            int delim = sAddr.indexOf('%');
                            return delim < 0 ? sAddr : sAddr.substring(0, delim);
                        }
                    }
                }
            }
        }
    } catch (Exception ex) {
    }
    // for now eat exceptions
    return "";
}
Also used : NetworkInterface(java.net.NetworkInterface) InetAddress(java.net.InetAddress)

Example 30 with NetworkInterface

use of java.net.NetworkInterface in project BeyondUPnP by kevinshine.

the class Utils method getMACAddress.

/**
     * Returns MAC address of the given interface name.
     *
     * @param interfaceName eth0, wlan0 or NULL=use first interface
     * @return mac address or empty string
     */
public static String getMACAddress(String interfaceName) {
    try {
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface intf : interfaces) {
            if (interfaceName != null) {
                if (!intf.getName().equalsIgnoreCase(interfaceName))
                    continue;
            }
            byte[] mac = intf.getHardwareAddress();
            if (mac == null)
                return "";
            StringBuilder buf = new StringBuilder();
            for (int idx = 0; idx < mac.length; idx++) buf.append(String.format("%02X:", mac[idx]));
            if (buf.length() > 0)
                buf.deleteCharAt(buf.length() - 1);
            return buf.toString();
        }
    } catch (Exception ex) {
    }
    // for now eat exceptions
    return "";
}
Also used : NetworkInterface(java.net.NetworkInterface)

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