参考文献
如何为Android应用提供全局的HttpDNS服务
上述链接描述到可以通过动态代理去hook,我根据思路自己实现了下
/**
* https://juejin.cn/post/6844903512401248270#heading-4
*/
public static void hookImpl() {
/**
*static final InetAddressImpl impl = new Inet6AddressImpl();
*/
Class inetAddressClass = InetAddress.class;
try {
Field impl = inetAddressClass.getDeclaredField("impl");
impl.setAccessible(true);
final Object oldObj = impl.get(null);
InvocationHandler invocationHandler = new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
LogUtils.ii(TAG, "method.getName() " + method.getName());
LogUtils.ii(TAG, "args " + Arrays.toString(args));
if ("lookupAllHostAddr".equals(method.getName())) {
//因为我存在多个域名地址
for (String host : NetRep.hosts) {
if (host.equals(args[0])) {
LogUtils.ii(TAG, "匹配域名");
InetAddress[] invoke = (InetAddress[]) method.invoke(oldObj, args);
//构建一个新的
InetAddress[] invokeNEW = new InetAddress[invoke.length + 1];
//加上自己的ip地址
InetAddress inetAddress = ip2InetAddress(NetRep.myIP);
//赋值在第一个上面
invokeNEW[0] = inetAddress;
//从1开始算
System.arraycopy(invoke, 0, invokeNEW, 1, invoke.length);
//从0开始算
//System.arraycopy(invoke, 0, invokeNEW, 0, invoke.length);
LogUtils.ii(TAG, "返回新集合");
return invokeNEW;
}
}
}
return method.invoke(oldObj, args);
}
};
Object newObj = Proxy.newProxyInstance(
inetAddressClass.getClassLoader(),
oldObj.getClass().getInterfaces(),
invocationHandler);
impl.set(null, newObj);
} catch (Throwable e) {
LogUtils.e(TAG, e);
}
}
把这代码放在application上进行初始化
|