Created
June 13, 2020 10:01
-
-
Save nICEnnnnnnnLee/1891c34b286a9b247f0682e44450fafa to your computer and use it in GitHub Desktop.
java 设置指定域名的ip解析
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.lang.reflect.Constructor; | |
import java.lang.reflect.Field; | |
import java.lang.reflect.InvocationTargetException; | |
import java.net.InetAddress; | |
import java.net.UnknownHostException; | |
import java.util.Map; | |
public class Test { | |
public static void main(String[] args) { | |
try { | |
Field field = InetAddress.class.getDeclaredField("addressCache"); | |
field.setAccessible(true); | |
Object addressCache = field.get(null); | |
// 获取Map | |
Field cacheMapField = addressCache.getClass().getDeclaredField("cache"); | |
cacheMapField.setAccessible(true); | |
Map cacheMap = (Map) cacheMapField.get(addressCache); | |
// 获取CacheEntry(内部类) Map 的 Value | |
Class<?> cls = Class.forName("java.net.InetAddress$CacheEntry"); | |
Constructor<?> constructor = cls.getDeclaredConstructor(InetAddress[].class, long.class); | |
constructor.setAccessible(true); | |
InetAddress[] ipAddr = new InetAddress[1]; | |
ipAddr[0] = getInetAddr("127.0.0.1"); | |
Object value = constructor.newInstance(ipAddr, -1); | |
// 设置host(永不过期) | |
synchronized (addressCache) { | |
cacheMap.put("www.baidu.com", value); | |
} | |
// 测试 | |
InetAddress addresses = InetAddress.getByName("www.baidu.com"); | |
System.out.println(addresses.getHostAddress()); | |
Thread.sleep(40000); | |
addresses = InetAddress.getByName("www.baidu.com"); | |
System.out.println(addresses.getHostAddress()); | |
// 还原可见性 | |
constructor.setAccessible(false); | |
field.setAccessible(false); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
static InetAddress getInetAddr(String ip) throws UnknownHostException { | |
String[] ipStr = ip.split("\\."); | |
byte[] ipBuf = new byte[4]; | |
for (int i = 0; i < 4; i++) { | |
ipBuf[i] = (byte) (Integer.parseInt(ipStr[i]) & 0xff); | |
} | |
return InetAddress.getByAddress(ipBuf); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment