| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
package android.net; |
| 18 |
|
| 19 |
import android.annotation.NonNull; |
| 20 |
import android.util.Log; |
| 21 |
|
| 22 |
import java.io.IOException; |
| 23 |
import java.net.InetSocketAddress; |
| 24 |
|
| 25 |
import javax.net.SocketFactory; |
| 26 |
import javax.net.ssl.SSLSocket; |
| 27 |
import javax.net.ssl.SSLSocketFactory; |
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
public class PrivateDnsConnectivityChecker { |
| 34 |
private static final String TAG = "NetworkUtils"; |
| 35 |
|
| 36 |
private static final int PRIVATE_DNS_PORT = 853; |
| 37 |
private static final int CONNECTION_TIMEOUT_MS = 5000; |
| 38 |
|
| 39 |
private PrivateDnsConnectivityChecker() { } |
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
public static boolean canConnectToPrivateDnsServer(@NonNull String hostname) { |
| 46 |
final SocketFactory factory = SSLSocketFactory.getDefault(); |
| 47 |
TrafficStats.setThreadStatsTagApp(); |
| 48 |
|
| 49 |
try (SSLSocket socket = (SSLSocket) factory.createSocket()) { |
| 50 |
socket.setSoTimeout(CONNECTION_TIMEOUT_MS); |
| 51 |
socket.connect(new InetSocketAddress(hostname, PRIVATE_DNS_PORT)); |
| 52 |
if (!socket.isConnected()) { |
| 53 |
Log.w(TAG, String.format("Connection to %s failed.", hostname)); |
| 54 |
return false; |
| 55 |
} |
| 56 |
socket.startHandshake(); |
| 57 |
Log.w(TAG, String.format("TLS handshake to %s succeeded.", hostname)); |
| 58 |
return true; |
| 59 |
} catch (IOException e) { |
| 60 |
Log.w(TAG, String.format("TLS handshake to %s failed.", hostname), e); |
| 61 |
return false; |
| 62 |
} |
| 63 |
} |
| 64 |
} |