一、需求說明
開發中經常需要做一些網絡請求,涉及到線上線下的灰度、正式環境切換,有時因爲服務的不同,那麼app內會存在多個域名的情況,甚至有些域名被添加到aar或者jar包中,修改起來也非常困難。一般的話利用fiddler或者charles去處理,然後修改電腦的域名映射,這種情況幾乎處理了很多需求問題,也是非常可靠實用的方案。當然,這種操作一般很適合測試人員,對於開發來說,顯的太繁重了。
那麼有沒有直接修改手機Hosts的方式呢?
早期的Android版本或者經過root的android系統都是可以實現的,但後期的版本經過大修,無論是解析還是權限,成本非常高,不過Android提供了另外一種方式是VpnService,其實可以通過VpnService可以去攔截,具體參考《PureHost開源項目》,這種要求具備協議編程的基礎,當然實用性更高,另外一種是Hook InetAddress解析實現,實現起來也比較容易,但只支持Android 7.0 之後的版本,當然本篇主要是第二種,主要目的是應對基本的環境切換問題。
開源地址:https://gitee.com/smartian_git/DnsHosts
二、InetAddress DNS解析
在JDK中,無論走哪種帶域名的網絡連接,都會毫無例外的走InetAdress中的實現,去查詢DNS,我們這裏Hook InetAddress中的實現
public class DnsInetAddress implements InvocationHandler {
private DnsHostsManager mDnsResoverManager;
private RealInvocationHandler mInvocationHandler;
public DnsInetAddress(DnsHostsManager dnsResoverManager) {
this.mDnsResoverManager = dnsResoverManager;
this.mInvocationHandler = newInvocationHandler();
}
private RealInvocationHandler newInvocationHandler() {
try {
return new RealInvocationHandler();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
public Object createProxyInstance(Object realImpl) {
try {
Class<?>[] interfaces = realImpl.getClass().getInterfaces();
return Proxy.newProxyInstance(DnsInetAddress.class.getClassLoader(), interfaces, this);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void hook() {
try {
if (mInvocationHandler == null) {
return;
}
Field addressImplField = mInvocationHandler.getAddressImplField();
if (addressImplField == null) {
return;
}
Object proxyInstance = createProxyInstance(mInvocationHandler.getAddressImpl());
if (proxyInstance == null) {
return;
}
addressImplField.set(InetAddress.class, proxyInstance);
} catch (IllegalAccessException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
boolean shouldHookProxy = mDnsResoverManager.shouldHookProxy(method, args);
if (shouldHookProxy) {
Object result = mDnsResoverManager.lookup(method.getName(), method.getParameterTypes(), args);
if (result != null) {
return result;
}
}
return mInvocationHandler.invoke(proxy, method, args);
}
static class RealInvocationHandler implements InvocationHandler {
private Object mAddressImpl_instance;
private Field addressImplField;
public RealInvocationHandler() throws NoSuchFieldException, IllegalAccessException {
this.addressImplField = getInetAddressImplField();
if (addressImplField != null) {
this.mAddressImpl_instance = addressImplField.get(null);
}
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
Object result = method.invoke(mAddressImpl_instance, args);
return result;
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}catch (Exception e){
throw e;
}
return null;
}
public Object getAddressImpl() {
return mAddressImpl_instance;
}
public Field getAddressImplField() {
return addressImplField;
}
}
public static Field getInetAddressImplField() throws NoSuchFieldException, IllegalAccessException {
Field InetAddress_impl = InetAddress.class.getDeclaredField("impl");
InetAddress_impl.setAccessible(true);
return InetAddress_impl;
}
}
攔截實現
public class DnsHookProxyImpl {
private final DnsHostList dnsHostList;
private static Method sHolderMethod = null;
public DnsHookProxyImpl(DnsHostList dnsHostList) {
this.dnsHostList = dnsHostList;
}
public InetAddress[] lookupAllHostAddr(String hostname, int netId) throws UnknownHostException {
boolean hostNameIsIpAddress = InetAddressUtils.isMatcherIpV4OrIpV6(hostname);
if(hostNameIsIpAddress){
return null;
}
String lookupIp = dnsHostList.lookup(hostname, netId);
if(TextUtils.isEmpty(lookupIp)){
return null;
}
InetAddress address = createInetAddress(hostname,lookupIp);
return new InetAddress[]{
address
};
}
private InetAddress createInetAddress(String hostname, String lookupIp) {
InetAddress inetAddress = null;
try {
if(InetAddressUtils.isIPv4LiteralAddress(lookupIp)) {
Constructor<Inet4Address> declaredConstructor = Inet4Address.class.getDeclaredConstructor(String.class, byte[].class);
declaredConstructor.setAccessible(true);
inetAddress = declaredConstructor.newInstance(hostname, InetAddressUtils.textToNumericFormatV4(lookupIp));
}else if(InetAddressUtils.isIPv6LiteralAddress(lookupIp)){
Constructor<Inet6Address> declaredConstructor = Inet6Address.class.getDeclaredConstructor(String.class, byte[].class);
declaredConstructor.setAccessible(true);
inetAddress = declaredConstructor.newInstance(hostname, InetAddressUtils.textToNumericFormatV6(lookupIp));
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return inetAddress;
}
public boolean canLookup() {
if(dnsHostList!=null && !dnsHostList.isEmpty()){
return true;
}
return false;
}
public final static String METHODS[] = {
"lookupAllHostAddr"
};
public boolean isHookMethod(String methodName) {
return Arrays.asList(METHODS).contains(methodName);
}
}
三、用法和測試
用法
Map<String,String> dnsMap = new HashMap<>(); dnsMap.put("www.baidu.com","127.0.0.1"); dnsMap.put("www.taobao.com", "2001:0db8:3c4d:0015:0000:0000:1a2f:1a2b"); DnsHostsManager.registerDns(dnsMap);
測試:
try { //被映射的域名 InetAddress baidu = InetAddress.getByName("www.baidu.com"); Log.d("DnsManager"," == " +baidu); InetAddress[] taobao = InetAddress.getAllByName("www.taobao.com"); Log.d("DnsManager"," == " +taobao[0]); //未被映射的域名,走原有解析 InetAddress tmall = InetAddress.getByName("www.tmall.com"); Log.d("DnsManager"," == " +tmall); InetAddress qq = InetAddress.getByName("www.qq.com"); Log.d("DnsManager"," == " +qq); } catch (Exception e) { e.printStackTrace(); }
測試結果
D/DnsManager: == www.baidu.com/127.0.0.1 D/DnsManager: == www.taobao.com/2001:db8:3c4d:15::1a2f:1a2b D/DnsManager: == www.tmall.com/27.221.93.231 D/DnsManager: == www.qq.com/220.194.120.49