Java 获取域名服务器地址

发布于 2016-12-06 / Java / 0条评论 / 1,281浏览

已测验

import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Map; /** * Created by denghb on 2016/12/6. */ public class AppTest { public static void main(String[] args) { System.out.println(getHostIP("www.sina.com.cn")); } /** * 获取单个ip * * @param domain * @return */ public static String getHostIP(final String domain) { return getHostIPs(domain)[0]; } /** * 清理缓存 * * @param domain * @return */ public static void clearIPCache(final String domain) { try { // 清除缓存数据 Class inetAddressClass = java.net.InetAddress.class; final java.lang.reflect.Field cacheField = inetAddressClass.getDeclaredField("addressCache"); cacheField.setAccessible(true); final Object obj = cacheField.get(inetAddressClass); Class cacheClazz = obj.getClass(); final java.lang.reflect.Field cachePolicyField = cacheClazz.getDeclaredField("policy"); final java.lang.reflect.Field cacheMapField = cacheClazz.getDeclaredField("cache"); cachePolicyField.setAccessible(true); cacheMapField.setAccessible(true); final Map cacheMap = (Map) cacheMapField.get(obj); cacheMap.remove(domain); } catch (IllegalAccessException e) { // TODO } catch (NoSuchFieldException e) { // TODO } } /** * 获取所有ip * * @param domain * @return */ public static String[] getHostIPs(final String domain) { // 清理缓存 clearIPCache(domain); String ips[] = new String[1]; try { // 获取IP地址 InetAddress[] addrs = InetAddress.getAllByName(domain); if (null != addrs) { int len = addrs.length; ips = new String[len]; for (int i = 0; i < len; i++) { ips[i] = addrs[i].getHostAddress(); } } } catch (UnknownHostException e) { // TODO } return ips; } }
评论
站长统计