/* * Copyright 2010 Brave New Software Project, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.shadowsocks.utils; import android.annotation.TargetApi; import android.content.Context; import android.net.ConnectivityManager; import android.net.LinkProperties; import android.os.Build; import java.lang.reflect.Method; import java.net.InetAddress; import java.util.ArrayList; import java.util.Collection; public class Dns { public static String getDnsResolver(Context context) throws Exception { Collection dnsResolvers = getDnsResolvers(context); if (dnsResolvers.isEmpty()) { throw new Exception("Couldn't find an active DNS resolver"); } String dnsResolver = dnsResolvers.iterator().next().toString(); if (dnsResolver.startsWith("/")) { dnsResolver = dnsResolver.substring(1); } return dnsResolver; } private static Collection getDnsResolvers(Context context) throws Exception { ArrayList addresses = new ArrayList(); ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); Class LinkPropertiesClass = Class.forName("android.net.LinkProperties"); Method getActiveLinkPropertiesMethod = ConnectivityManager.class.getMethod("getActiveLinkProperties"); Object linkProperties = getActiveLinkPropertiesMethod.invoke(connectivityManager); if (linkProperties != null) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { Method getDnsesMethod = LinkPropertiesClass.getMethod("getDnses"); Collection dnses = (Collection)getDnsesMethod.invoke(linkProperties); for (Object dns : dnses) { addresses.add((InetAddress)dns); } } else { addresses.addAll(((LinkProperties) linkProperties).getDnsServers()); } } return addresses; } }