blob: d844824cf5c703bcf9af25cf6de9179477e319d9 (
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
64
65
66
67
68
69
70
71
72
73
74
75
76
|
package de.pixart.messenger.utils;
import android.annotation.TargetApi;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.LinkProperties;
import android.net.Network;
import android.net.RouteInfo;
import android.os.Build;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
import de.measite.minidns.dnsserverlookup.AbstractDNSServerLookupMechanism;
import de.measite.minidns.dnsserverlookup.AndroidUsingExec;
public class AndroidUsingLinkProperties extends AbstractDNSServerLookupMechanism {
private final Context context;
protected AndroidUsingLinkProperties(Context context) {
super(AndroidUsingLinkProperties.class.getSimpleName(), AndroidUsingExec.PRIORITY - 1);
this.context = context;
}
@Override
public boolean isAvailable() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
}
@Override
@TargetApi(21)
public String[] getDnsServerAddresses() {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
Network[] networks = connectivityManager == null ? null : connectivityManager.getAllNetworks();
if (networks == null) {
return new String[0];
}
List<String> servers = new ArrayList<>();
for (Network network : networks) {
LinkProperties linkProperties = connectivityManager.getLinkProperties(network);
if (linkProperties != null) {
if (hasDefaultRoute(linkProperties)) {
servers.addAll(0, getIPv4First(linkProperties.getDnsServers()));
} else {
servers.addAll(getIPv4First(linkProperties.getDnsServers()));
}
}
}
return servers.toArray(new String[servers.size()]);
}
private static List<String> getIPv4First(List<InetAddress> in) {
List<String> out = new ArrayList<>();
for (InetAddress addr : in) {
if (addr instanceof Inet4Address) {
out.add(0, addr.getHostAddress());
} else {
out.add(addr.getHostAddress());
}
}
return out;
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static boolean hasDefaultRoute(LinkProperties linkProperties) {
for (RouteInfo route : linkProperties.getRoutes()) {
if (route.isDefaultRoute()) {
return true;
}
}
return false;
}
}
|