aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/de/pixart/messenger/xmpp/jingle/DirectConnectionUtils.java
blob: ee2e0f0fe0218740f03a19513ffbd53aa6842af3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package de.pixart.messenger.xmpp.jingle;

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.UUID;

import rocks.xmpp.addr.Jid;

public class DirectConnectionUtils {

    private static List<InetAddress> getLocalAddresses() {
        final List<InetAddress> addresses = new ArrayList<>();
        final Enumeration<NetworkInterface> interfaces;
        try {
            interfaces = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
            return addresses;
        }
        while (interfaces.hasMoreElements()) {
            NetworkInterface networkInterface = interfaces.nextElement();
            final Enumeration<InetAddress> inetAddressEnumeration = networkInterface.getInetAddresses();
            while (inetAddressEnumeration.hasMoreElements()) {
                final InetAddress inetAddress = inetAddressEnumeration.nextElement();
                if (inetAddress.isLoopbackAddress() || inetAddress.isLinkLocalAddress()) {
                    continue;
                }
                if (inetAddress instanceof Inet6Address) {
                    //let's get rid of scope
                    try {
                        addresses.add(Inet6Address.getByAddress(inetAddress.getAddress()));
                    } catch (UnknownHostException e) {
                        //ignored
                    }
                } else {
                    addresses.add(inetAddress);
                }
            }
        }
        return addresses;
    }

    public static List<JingleCandidate> getLocalCandidates(Jid jid) {
        SecureRandom random = new SecureRandom();
        ArrayList<JingleCandidate> candidates = new ArrayList<>();
        for (InetAddress inetAddress : getLocalAddresses()) {
            final JingleCandidate candidate = new JingleCandidate(UUID.randomUUID().toString(), true);
            candidate.setHost(inetAddress.getHostAddress());
            candidate.setPort(random.nextInt(60000) + 1024);
            candidate.setType(JingleCandidate.TYPE_DIRECT);
            candidate.setJid(jid);
            candidate.setPriority(8257536 + candidates.size());
            candidates.add(candidate);
        }
        return candidates;
    }
}