├── LICENSE ├── README.md ├── pom.xml └── src ├── main ├── java │ └── io │ │ └── leopard │ │ └── javahost │ │ ├── AutoUnitRunnable.java │ │ ├── Config.java │ │ ├── Dns.java │ │ ├── Hosts.java │ │ ├── JavaHost.java │ │ ├── impl │ │ ├── AbstractDns.java │ │ ├── AbstractHosts.java │ │ ├── ConfigClasspathImpl.java │ │ ├── ConfigImpl.java │ │ ├── DnsImpl.java │ │ ├── HostsCacheImpl.java │ │ └── HostsImpl.java │ │ └── model │ │ └── Host.java └── resources │ └── autounit.properties └── test ├── java └── io │ └── leopard │ └── javahost │ ├── Ipv6Test.java │ ├── JavaHostTest.java │ └── impl │ ├── DnsImplTest.java │ └── HostsImplTest.java └── resources └── test.txt /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # javahost 2 | JVM虚拟DNS,开发期间可以省去hosts文件配置 3 | 4 | 5 | 使用文档 6 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | io.leopard 4 | javahost 5 | 0.9.11-SNAPSHOT 6 | 7 | JavaHost 8 | JVM虚拟DNS,开发期间可以省去hosts文件配置 9 | https://github.com/tanhaichao/javahost 10 | 2014 11 | 12 | 13 | io.leopard.depend 14 | depend 15 | 0.9.6 16 | 17 | 18 | 19 | https://github.com/tanhaichao/javahost 20 | scm:svn:https://github.com/tanhaichao/javahost/trunk 21 | scm:svn:https://github.com/tanhaichao/javahost/trunk 22 | 23 | 24 | 25 | GitHub Issues 26 | https://github.com/tanhaichao/javahost/issues 27 | 28 | 29 | 30 | 31 | junit 32 | junit 33 | test 34 | 35 | 36 | 37 | 38 | 39 | org.springframework 40 | spring-core 41 | provided 42 | 43 | 44 | commons-io 45 | commons-io 46 | provided 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /src/main/java/io/leopard/javahost/AutoUnitRunnable.java: -------------------------------------------------------------------------------- 1 | package io.leopard.javahost; 2 | 3 | import java.io.IOException; 4 | import java.io.InputStream; 5 | import java.util.Properties; 6 | 7 | import io.leopard.javahost.impl.ConfigImpl; 8 | 9 | /** 10 | * 使用到AutoUnit时自动调用. 11 | * 12 | * @author 阿海 13 | * 14 | */ 15 | public class AutoUnitRunnable implements Runnable { 16 | 17 | @Override 18 | public void run() { 19 | try { 20 | Config config = new ConfigImpl(); 21 | InputStream input = config.find(); 22 | Properties props = new Properties(); 23 | props.load(input); 24 | input.close(); 25 | JavaHost.updateVirtualDns(props); 26 | } 27 | catch (IOException e) { 28 | String message = "host文件[classpath:/dev/dns.properties]不存在."; 29 | System.out.println(message); 30 | e.printStackTrace(); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/io/leopard/javahost/Config.java: -------------------------------------------------------------------------------- 1 | package io.leopard.javahost; 2 | 3 | import java.io.IOException; 4 | import java.io.InputStream; 5 | 6 | public interface Config { 7 | 8 | InputStream find() throws IOException; 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/io/leopard/javahost/Dns.java: -------------------------------------------------------------------------------- 1 | package io.leopard.javahost; 2 | 3 | import io.leopard.javahost.model.Host; 4 | 5 | import java.util.List; 6 | 7 | /** 8 | * 虚拟DNS接口. 9 | * 10 | * @author 阿海 11 | * 12 | */ 13 | public interface Dns { 14 | 15 | /** 16 | * 设置域名解析. 17 | * 18 | * @param host 19 | * 域名 20 | * @param ip 21 | * IP数组 22 | * @return 23 | */ 24 | boolean update(String host, String ip); 25 | 26 | /** 27 | * 设置域名解析. 28 | * 29 | * @param host 30 | * 域名 31 | * @param ips 32 | * IP数组 33 | * @return 34 | */ 35 | boolean update(String host, String[] ips); 36 | 37 | /** 38 | * 删除域名解析. 39 | * 40 | * @param host 41 | * 域名 42 | * @param ip 43 | * IP数组 44 | * @return 45 | */ 46 | boolean remove(String host); 47 | 48 | /** 49 | * 解析域名. 50 | * 51 | * @param host 52 | * 域名 53 | * @return IP 54 | */ 55 | String queryIp(String host); 56 | 57 | /** 58 | * 解析域名. 59 | * 60 | * @param host 61 | * 域名 62 | * @return Host对象 63 | */ 64 | Host query(String host); 65 | 66 | /** 67 | * 获取所有虚拟DNS记录. 68 | * 69 | * @return 70 | */ 71 | List list(); 72 | 73 | /** 74 | * 获取所有虚拟DNS记录. 75 | * 76 | * @param host域名 77 | * @return 78 | */ 79 | List list(String host); 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/io/leopard/javahost/Hosts.java: -------------------------------------------------------------------------------- 1 | package io.leopard.javahost; 2 | 3 | import io.leopard.javahost.model.Host; 4 | 5 | import java.util.List; 6 | 7 | /** 8 | * Hosts文件解析接口. 9 | * 10 | * @author 阿海 11 | * 12 | * 13 | */ 14 | public interface Hosts { 15 | 16 | /** 17 | * 获取所有hosts文件配置的记录. 18 | * 19 | * @return hosts文件记录 20 | */ 21 | List list(); 22 | 23 | /** 24 | * 判断域名是否存在. 25 | * 26 | * @param host 27 | * 域名 28 | * @return IP 29 | */ 30 | boolean exist(String host); 31 | 32 | /** 33 | * 根据域名获取IP. 34 | * 35 | * @param host 36 | * 域名 37 | * @return IP 38 | */ 39 | String query(String host); 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/io/leopard/javahost/JavaHost.java: -------------------------------------------------------------------------------- 1 | package io.leopard.javahost; 2 | 3 | import io.leopard.javahost.impl.DnsImpl; 4 | import io.leopard.javahost.impl.HostsCacheImpl; 5 | import io.leopard.javahost.model.Host; 6 | 7 | import java.net.InetAddress; 8 | import java.net.UnknownHostException; 9 | import java.util.ArrayList; 10 | import java.util.Iterator; 11 | import java.util.List; 12 | import java.util.Map; 13 | import java.util.Map.Entry; 14 | import java.util.Properties; 15 | import java.util.Random; 16 | 17 | /** 18 | * JavaHost(JVM虚拟DNS)接口 util类.
19 | * 20 | * IP查找顺序:虚拟DNS -> hosts文件 -> DNS服务器. 21 | * 22 | * @author 阿海 23 | * 24 | */ 25 | public class JavaHost { 26 | 27 | private static Dns dns = new DnsImpl(); 28 | private static Hosts hosts = new HostsCacheImpl(); 29 | 30 | /** 31 | * 获取虚拟DNS接口 32 | * 33 | * @return 34 | */ 35 | public static Dns getDns() { 36 | return dns; 37 | } 38 | 39 | /** 40 | * 获取hosts文件解析接口 41 | * 42 | * @return 43 | */ 44 | public static Hosts getHosts() { 45 | return hosts; 46 | } 47 | 48 | /** 49 | * 更新虚拟DNS域名指向. 50 | * 51 | * @param host 52 | * 域名 53 | * @param ip 54 | * IP 55 | * @return 56 | */ 57 | public static boolean updateVirtualDns(String host, String ip) { 58 | return dns.update(host, ip); 59 | } 60 | 61 | /** 62 | * 更新虚拟DNS域名指向. 63 | * 64 | * @param host 65 | * 域名 66 | * @param ip 67 | * IP数组 68 | * @return 69 | */ 70 | public static boolean updateVirtualDns(String host, String[] ips) { 71 | return dns.update(host, ips); 72 | } 73 | 74 | /** 75 | * 更新虚拟DNS域名指向. 76 | * 77 | * @param properties 78 | * key为域名,value为IP地址 79 | * 80 | * @return 更新虚拟DNS记录的条数 81 | */ 82 | public static int updateVirtualDns(Properties properties) { 83 | Iterator> iterator = properties.entrySet().iterator(); 84 | int count = 0; 85 | while (iterator.hasNext()) { 86 | Entry entry = iterator.next(); 87 | if (!(entry.getKey() instanceof String) || !(entry.getValue() instanceof String)) { 88 | continue; 89 | } 90 | String host = ((String) entry.getKey()).trim(); 91 | String ip = ((String) entry.getValue()).trim(); 92 | 93 | if (!isLocalHost(host)) { 94 | count += updateVirtualDnsByStrings(host, ip); 95 | } 96 | } 97 | return count; 98 | } 99 | 100 | protected static int updateVirtualDnsByStrings(String host, String ipList) { 101 | List list = new ArrayList(); 102 | for (String ip : ipList.split(",")) { 103 | ip = ip.trim(); 104 | // if (isValidIp(ip)) { 105 | if (ip.length() > 0) { 106 | list.add(ip); 107 | } 108 | // } 109 | } 110 | if (!list.isEmpty()) { 111 | String[] ips = new String[list.size()]; 112 | list.toArray(ips); 113 | JavaHost.updateVirtualDns(host, ips); 114 | } 115 | return list.size(); 116 | } 117 | 118 | /** 119 | * 打印所有虚拟DNS记录. 120 | */ 121 | public static void printAllVirtualDns() { 122 | List list = dns.list(); 123 | for (Host host : list) { 124 | System.out.println(host); 125 | } 126 | } 127 | 128 | public static int updateVirtualDns(Map map) { 129 | Iterator> iterator = map.entrySet().iterator(); 130 | int count = 0; 131 | while (iterator.hasNext()) { 132 | Entry entry = iterator.next(); 133 | String host = entry.getKey().trim(); 134 | String ip = entry.getValue().trim(); 135 | if (!isLocalHost(host)) { 136 | count += updateVirtualDnsByStrings(host, ip); 137 | } 138 | } 139 | return count; 140 | } 141 | 142 | // /** 143 | // * 判断是否合法IP. 144 | // * 145 | // * @param ip 146 | // * @return 147 | // */ 148 | // protected static boolean isValidIp(String ip) { 149 | // if (ip == null || ip.length() == 0) { 150 | // return false; 151 | // } 152 | // String[] strs = ip.split("\\."); 153 | // if (strs.length != 4) { 154 | // return false; 155 | // } 156 | // for (int i = 0; i < strs.length; i++) { 157 | // int num = Integer.parseInt(strs[i]); 158 | // if (num > 255) { 159 | // return false; 160 | // } 161 | // } 162 | // return true; 163 | // } 164 | 165 | /** 166 | * 根据域名查询IP,多IP时随机返回1个(查询范围:包括hosts文件、DNS服务器、虚拟DNS). 167 | * 168 | * @param host 169 | * 域名 170 | * @return IP 171 | */ 172 | public static String queryIp(String host) { 173 | InetAddress[] addresses; 174 | try { 175 | addresses = InetAddress.getAllByName(host); 176 | } 177 | catch (UnknownHostException e) { 178 | return null; 179 | } 180 | // System.out.println("len:" + addresses.length); 181 | if (addresses.length == 1) { 182 | return addresses[0].getHostAddress(); 183 | } 184 | else { 185 | // 多IP时,随机返回一个 186 | int random = new Random().nextInt(addresses.length); 187 | return addresses[random].getHostAddress(); 188 | } 189 | } 190 | 191 | /** 192 | * 根据域名查询IP,多IP时只返回第一个(查询范围:包括hosts文件、DNS服务器、虚拟DNS). 193 | * 194 | * @param host 195 | * 域名 196 | * @return IP 197 | */ 198 | public static String getIp(String host) { 199 | InetAddress address; 200 | try { 201 | address = InetAddress.getByName(host); 202 | } 203 | catch (UnknownHostException e) { 204 | return null; 205 | } 206 | return address.getHostAddress(); 207 | } 208 | 209 | /** 210 | * 从本地hosts文件解析域名. 211 | * 212 | * @param host 213 | * 域名 214 | * @return IP 215 | */ 216 | public static String queryIpByLocalHosts(String host) { 217 | return hosts.query(host); 218 | } 219 | 220 | /** 221 | * 从虚拟DNS解析域名. 222 | * 223 | * @param host 224 | * 域名 225 | * @return IP 226 | */ 227 | public static String queryIpByVirtualDns(String host) { 228 | return dns.queryIp(host); 229 | } 230 | 231 | /** 232 | * 是否在hosts文件配置的域名? 233 | * 234 | * @param host 235 | * 域名 236 | * @return 237 | */ 238 | public static boolean isLocalHost(String host) { 239 | return hosts.exist(host); 240 | } 241 | } 242 | -------------------------------------------------------------------------------- /src/main/java/io/leopard/javahost/impl/AbstractDns.java: -------------------------------------------------------------------------------- 1 | package io.leopard.javahost.impl; 2 | 3 | import io.leopard.javahost.Dns; 4 | import io.leopard.javahost.model.Host; 5 | 6 | import java.lang.reflect.Constructor; 7 | import java.lang.reflect.Field; 8 | import java.net.InetAddress; 9 | import java.util.Map; 10 | 11 | /** 12 | * 虚拟DNS抽象实现类. 13 | * 14 | * @author 阿海 15 | * 16 | */ 17 | public abstract class AbstractDns implements Dns { 18 | 19 | protected static final long ABOUT_YEAR = 3600 * 24 * 1000L * 365;// 大约1年的毫秒数 20 | private static final long EXPIRATION = ABOUT_YEAR * 10;// 大约10年失效 21 | 22 | @SuppressWarnings({ "rawtypes", "unchecked" }) 23 | protected Map getAddressCache() { 24 | try { 25 | final Field cacheField = InetAddress.class.getDeclaredField("addressCache"); 26 | cacheField.setAccessible(true); 27 | final Object addressCache = cacheField.get(InetAddress.class); 28 | 29 | Class clazz = addressCache.getClass(); 30 | final Field cacheMapField = clazz.getDeclaredField("cache"); 31 | cacheMapField.setAccessible(true); 32 | return (Map) cacheMapField.get(addressCache); 33 | } 34 | catch (Exception e) { 35 | throw new RuntimeException(e.getMessage(), e); 36 | } 37 | } 38 | 39 | // private byte[] toBytes(String ip) { 40 | // byte[] addr = new byte[4]; 41 | // { 42 | // String[] strs = ip.split("\\."); 43 | // for (int i = 0; i < strs.length; i++) { 44 | // // System.out.println("strs[i]:" + strs[i]); 45 | // addr[i] = (byte) Integer.parseInt(strs[i]); 46 | // } 47 | // } 48 | // return addr; 49 | // } 50 | 51 | // static final class CacheEntry { 52 | // 53 | // CacheEntry(InetAddress[] addresses, long expiration) { 54 | // this.addresses = addresses; 55 | // this.expiration = expiration; 56 | // } 57 | // 58 | // InetAddress[] addresses; 59 | // long expiration; 60 | // } 61 | protected Host[] toHost(Object entry) { 62 | if (entry == null) { 63 | throw new NullPointerException("entry不能为空."); 64 | } 65 | try { 66 | Class clazz = entry.getClass(); 67 | 68 | long expiration; 69 | { 70 | Field field = clazz.getDeclaredField("expiration"); 71 | field.setAccessible(true); 72 | expiration = (Long) field.get(entry); 73 | } 74 | InetAddress[] addresses; 75 | { 76 | Field field = clazz.getDeclaredField("addresses"); 77 | field.setAccessible(true); 78 | addresses = (InetAddress[]) field.get(entry); 79 | } 80 | Host[] hosts = new Host[addresses.length]; 81 | for (int i = 0; i < addresses.length; i++) { 82 | InetAddress address = (InetAddress) addresses[i]; 83 | Host host = new Host(); 84 | host.setExpiration(expiration); 85 | host.setHost(address.getHostName()); 86 | host.setIp(address.getHostAddress()); 87 | hosts[i] = host; 88 | } 89 | return hosts; 90 | } 91 | catch (Exception e) { 92 | throw new RuntimeException(e.getMessage(), e); 93 | } 94 | } 95 | 96 | // static final class CacheEntry { 97 | // 98 | // CacheEntry(InetAddress[] addresses, long expiration) { 99 | // this.addresses = addresses; 100 | // this.expiration = expiration; 101 | // } 102 | // 103 | // InetAddress[] addresses; 104 | // long expiration; 105 | // } 106 | protected Object createCacheEntry(String host, String[] ips) { 107 | try { 108 | long expiration = System.currentTimeMillis() + EXPIRATION;// 10年失效 109 | InetAddress[] addresses = new InetAddress[ips.length]; 110 | for (int i = 0; i < addresses.length; i++) { 111 | // addresses[i] = InetAddress.getByAddress(host, toBytes(ips[i])); 112 | addresses[i] = InetAddress.getByAddress(host, InetAddress.getByName(ips[i]).getAddress()); 113 | } 114 | String className = "java.net.InetAddress$CacheEntry"; 115 | Class clazz = Class.forName(className); 116 | Constructor constructor = clazz.getDeclaredConstructors()[0]; 117 | constructor.setAccessible(true); 118 | return constructor.newInstance(addresses, expiration); 119 | } 120 | catch (Exception e) { 121 | throw new RuntimeException(e.getMessage(), e); 122 | } 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /src/main/java/io/leopard/javahost/impl/AbstractHosts.java: -------------------------------------------------------------------------------- 1 | package io.leopard.javahost.impl; 2 | 3 | import io.leopard.javahost.Hosts; 4 | import io.leopard.javahost.model.Host; 5 | 6 | import java.io.BufferedReader; 7 | import java.io.FileReader; 8 | import java.io.IOException; 9 | import java.util.ArrayList; 10 | import java.util.List; 11 | 12 | /** 13 | * Hosts文件解析抽象实现. 14 | * 15 | * @author 阿海 16 | * 17 | */ 18 | public abstract class AbstractHosts implements Hosts { 19 | 20 | /** 21 | * 获取hosts文件路径. 22 | * 23 | * @return hosts文件路径 24 | */ 25 | protected String getHostsPath() { 26 | String path; 27 | if (System.getProperty("os.name").startsWith("Windows")) { 28 | path = "c:/windows/System32/drivers/etc/hosts"; 29 | } 30 | else { 31 | path = "/etc/hosts"; 32 | } 33 | return path; 34 | } 35 | 36 | /** 37 | * 读取hosts文件内容. 38 | * 39 | * @return hosts文件内容 40 | * @throws IOException 41 | */ 42 | protected String readHostsFile() throws IOException { 43 | String path = this.getHostsPath(); 44 | BufferedReader reader = new BufferedReader(new FileReader(path)); 45 | StringBuilder sb = new StringBuilder(); 46 | String line; 47 | while ((line = reader.readLine()) != null) { 48 | sb.append(line).append("\n"); 49 | } 50 | reader.close(); 51 | return sb.toString(); 52 | } 53 | 54 | protected List parseLine(String line) { 55 | line = line.trim(); 56 | line = line.replaceFirst("#.*$", "");// 过滤注释 57 | List list = new ArrayList(); 58 | if (line.length() == 0) { 59 | return list; 60 | } 61 | 62 | String[] hosts = line.split("\\s+"); 63 | if (hosts.length < 2) { 64 | throw new RuntimeException("非法host记录[" + line + "]."); 65 | } 66 | for (int i = 1; i < hosts.length; i++) { 67 | Host host = new Host(); 68 | host.setIp(hosts[0]); 69 | host.setHost(hosts[i]); 70 | list.add(host); 71 | } 72 | return list; 73 | } 74 | 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/io/leopard/javahost/impl/ConfigClasspathImpl.java: -------------------------------------------------------------------------------- 1 | package io.leopard.javahost.impl; 2 | 3 | import java.io.FileNotFoundException; 4 | import java.io.IOException; 5 | import java.io.InputStream; 6 | 7 | import org.springframework.core.io.Resource; 8 | import org.springframework.core.io.support.PathMatchingResourcePatternResolver; 9 | import org.springframework.core.io.support.ResourcePatternResolver; 10 | 11 | import io.leopard.javahost.Config; 12 | 13 | public class ConfigClasspathImpl implements Config { 14 | 15 | @Override 16 | public InputStream find() throws IOException { 17 | ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); 18 | Resource[] resources; 19 | try { 20 | resources = resolver.getResources("classpath*:/dev/dns.properties"); 21 | } 22 | catch (IOException e) { 23 | e.printStackTrace(); 24 | throw new FileNotFoundException("classpath*:/dev/dns.properties"); 25 | } 26 | for (Resource resource : resources) { 27 | try { 28 | InputStream is = resource.getInputStream(); 29 | return is; 30 | } 31 | catch (IOException e) { 32 | e.printStackTrace(); 33 | throw new RuntimeException(e.getMessage(), e); 34 | } 35 | } 36 | throw new FileNotFoundException("classpath*:/dev/dns.properties"); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/io/leopard/javahost/impl/ConfigImpl.java: -------------------------------------------------------------------------------- 1 | package io.leopard.javahost.impl; 2 | 3 | import java.io.FileNotFoundException; 4 | import java.io.IOException; 5 | import java.io.InputStream; 6 | import java.net.HttpURLConnection; 7 | import java.net.URL; 8 | import java.net.URLConnection; 9 | import java.util.Enumeration; 10 | 11 | import io.leopard.javahost.Config; 12 | 13 | public class ConfigImpl implements Config { 14 | 15 | @Override 16 | public InputStream find() throws IOException { 17 | InputStream input; 18 | try { 19 | input = this.findInternal(); 20 | } 21 | catch (IOException e) { 22 | input = null; 23 | } 24 | if (input == null) { 25 | try { 26 | input = this.findByClasspath(); 27 | } 28 | catch (Exception e) { 29 | throw new FileNotFoundException("classpath*:/dev/dns.properties"); 30 | } 31 | } 32 | return input; 33 | } 34 | 35 | protected InputStream findByClasspath() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException { 36 | @SuppressWarnings("unchecked") 37 | Class clazz = (Class) Class.forName("io.leopard.javahost.impl.ConfigClasspathImpl"); 38 | Config config = clazz.newInstance(); 39 | return config.find(); 40 | } 41 | 42 | protected InputStream findInternal() throws IOException { 43 | Enumeration urls = this.getClass().getClassLoader().getResources("dev/dns.properties"); 44 | URL url = null; 45 | if (urls.hasMoreElements()) { 46 | url = urls.nextElement(); 47 | } 48 | else { 49 | throw new FileNotFoundException("classpath:/dev/dns.properties"); 50 | // String message = "host文件[classpath:/dev/dns.properties]不存在."; 51 | // System.out.println(message); 52 | // return null; 53 | } 54 | URLConnection conn = null; 55 | try { 56 | conn = url.openConnection(); 57 | InputStream input = conn.getInputStream(); 58 | return input; 59 | } 60 | catch (IOException e) { 61 | if (conn != null && conn instanceof HttpURLConnection) { 62 | ((HttpURLConnection) conn).disconnect(); 63 | } 64 | return null; 65 | } 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/io/leopard/javahost/impl/DnsImpl.java: -------------------------------------------------------------------------------- 1 | package io.leopard.javahost.impl; 2 | 3 | import io.leopard.javahost.model.Host; 4 | 5 | import java.util.ArrayList; 6 | import java.util.Iterator; 7 | import java.util.List; 8 | import java.util.Map.Entry; 9 | import java.util.Random; 10 | 11 | /** 12 | * 虚拟DNS实现类 13 | * 14 | * @author 阿海 15 | * 16 | */ 17 | public class DnsImpl extends AbstractDns { 18 | 19 | @Override 20 | public boolean update(String host, String ip) { 21 | return this.update(host, new String[] { ip }); 22 | } 23 | 24 | @Override 25 | public boolean update(String host, String[] ips) { 26 | Object entry = createCacheEntry(host, ips); 27 | getAddressCache().put(host, entry); 28 | return true; 29 | } 30 | 31 | @Override 32 | public boolean remove(String host) { 33 | Object obj = getAddressCache().remove(host); 34 | return (obj != null); 35 | } 36 | 37 | @Override 38 | public String queryIp(String host) { 39 | Host bean = this.query(host); 40 | if (bean == null) { 41 | return null; 42 | } 43 | return bean.getHost(); 44 | } 45 | 46 | @Override 47 | public Host query(String host) { 48 | Object entry = getAddressCache().get(host); 49 | if (entry == null) { 50 | return null; 51 | } 52 | Host[] hosts = super.toHost(entry); 53 | Host bean = hosts[new Random().nextInt(hosts.length)];// 随机获取一个host 54 | if (isVirtualDns(bean)) { 55 | return bean; 56 | } 57 | return null; 58 | } 59 | 60 | /** 61 | * 判断是否虚拟DNS设置的host. 62 | * 63 | * @param host 64 | * DNS对象 65 | * @return 66 | */ 67 | protected boolean isVirtualDns(Host host) { 68 | long millis = host.getExpiration() - System.currentTimeMillis(); 69 | // JVM的DNS缓存默认是30秒过期,如果过期时间大于1年则表示自定义的域名解析记录 70 | // 在要求特别准确的情况下请注意:如果自定义了JVM DNS缓存时间超过1年,则会返回错误数据. 71 | return (millis > ABOUT_YEAR); 72 | } 73 | 74 | @Override 75 | public List list() { 76 | List list = new ArrayList(); 77 | Iterator> iterator = getAddressCache().entrySet().iterator(); 78 | while (iterator.hasNext()) { 79 | Entry entry = iterator.next(); 80 | Host[] hosts = super.toHost(entry.getValue()); 81 | for (Host host : hosts) { 82 | if (isVirtualDns(host)) { 83 | list.add(host); 84 | } 85 | } 86 | } 87 | return list; 88 | } 89 | 90 | @Override 91 | public List list(String host) { 92 | Object entry = getAddressCache().get(host); 93 | if (entry == null) { 94 | return null; 95 | } 96 | Host[] hosts = super.toHost(entry); 97 | List list = new ArrayList(); 98 | for (Host bean : hosts) { 99 | if (isVirtualDns(bean)) { 100 | list.add(bean); 101 | } 102 | } 103 | return list; 104 | } 105 | 106 | } 107 | -------------------------------------------------------------------------------- /src/main/java/io/leopard/javahost/impl/HostsCacheImpl.java: -------------------------------------------------------------------------------- 1 | package io.leopard.javahost.impl; 2 | 3 | import io.leopard.javahost.model.Host; 4 | 5 | import java.util.List; 6 | 7 | /** 8 | * Hosts文件解析缓存实现类. 9 | * 10 | * @author 阿海 11 | * 12 | */ 13 | public class HostsCacheImpl extends HostsImpl { 14 | private List list = null; 15 | 16 | @Override 17 | public List list() { 18 | if (list != null) { 19 | return list; 20 | } 21 | list = super.list(); 22 | return list; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/io/leopard/javahost/impl/HostsImpl.java: -------------------------------------------------------------------------------- 1 | package io.leopard.javahost.impl; 2 | 3 | import io.leopard.javahost.model.Host; 4 | 5 | import java.io.IOException; 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | 9 | /** 10 | * Hosts文件解析实现类. 11 | * 12 | * @author 阿海 13 | * 14 | */ 15 | public class HostsImpl extends AbstractHosts { 16 | 17 | @Override 18 | public List list() { 19 | String content; 20 | try { 21 | content = readHostsFile(); 22 | } 23 | catch (IOException e) { 24 | throw new RuntimeException(e.getMessage(), e); 25 | } 26 | // System.out.println("content:" + content); 27 | String[] lines = content.split("\n"); 28 | List list = new ArrayList(); 29 | for (String line : lines) { 30 | list.addAll(this.parseLine(line)); 31 | } 32 | return list; 33 | } 34 | 35 | @Override 36 | public boolean exist(String host) { 37 | String ip = this.query(host); 38 | return (ip != null); 39 | } 40 | 41 | @Override 42 | public String query(String host) { 43 | List list = this.list(); 44 | for (Host bean : list) { 45 | if (bean.getHost().equals(host)) { 46 | return bean.getIp(); 47 | } 48 | } 49 | return null; 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/io/leopard/javahost/model/Host.java: -------------------------------------------------------------------------------- 1 | package io.leopard.javahost.model; 2 | 3 | /** 4 | * Host Model. 5 | * 6 | * @author 阿海 7 | * 8 | */ 9 | public class Host { 10 | private String host; 11 | private String ip; 12 | private long expiration;// 过期时间 13 | 14 | public String getHost() { 15 | return host; 16 | } 17 | 18 | public void setHost(String host) { 19 | this.host = host; 20 | } 21 | 22 | public String getIp() { 23 | return ip; 24 | } 25 | 26 | public void setIp(String ip) { 27 | this.ip = ip; 28 | } 29 | 30 | public long getExpiration() { 31 | return expiration; 32 | } 33 | 34 | public void setExpiration(long expiration) { 35 | this.expiration = expiration; 36 | } 37 | 38 | @Override 39 | public String toString() { 40 | return "JavaHost [host=" + host + ", ip=" + ip + "]"; 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/main/resources/autounit.properties: -------------------------------------------------------------------------------- 1 | order=1 2 | 3 | integration.run.1=io.leopard.javahost.AutoUnitRunnable 4 | -------------------------------------------------------------------------------- /src/test/java/io/leopard/javahost/Ipv6Test.java: -------------------------------------------------------------------------------- 1 | package io.leopard.javahost; 2 | 3 | import java.net.Inet6Address; 4 | import java.net.InetAddress; 5 | import java.net.UnknownHostException; 6 | import java.util.HashMap; 7 | import java.util.Map; 8 | 9 | import org.junit.Test; 10 | 11 | public class Ipv6Test { 12 | 13 | @Test 14 | public void ipv6() throws UnknownHostException { 15 | InetAddress address = Inet6Address.getByName("ipv6.leopard.io"); 16 | String ip = address.getHostAddress(); 17 | System.out.println("ip:" + ip); 18 | 19 | JavaHost.queryIp("leopard.io"); 20 | 21 | Map map = new HashMap(); 22 | map.put("javahost1.leopard.io", "127.0.0.1"); 23 | map.put("javahost2.leopard.io", "127.0.0.2"); 24 | map.put("javahost6.leopard.io", "fe80::a178:9e5e:47d:5df3%14"); 25 | 26 | JavaHost.updateVirtualDns(map); 27 | JavaHost.printAllVirtualDns(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/test/java/io/leopard/javahost/JavaHostTest.java: -------------------------------------------------------------------------------- 1 | package io.leopard.javahost; 2 | 3 | import io.leopard.javahost.model.Host; 4 | 5 | import java.util.HashMap; 6 | import java.util.List; 7 | import java.util.Map; 8 | 9 | import org.junit.Assert; 10 | import org.junit.Test; 11 | 12 | public class JavaHostTest { 13 | 14 | @Test 15 | public void queryForIp() { 16 | Assert.assertEquals("112.126.75.27", JavaHost.queryIp("leopard2e.leopard.io")); 17 | } 18 | 19 | @Test 20 | public void isValidIp() { 21 | // Assert.assertTrue(JavaHost.isValidIp("255.255.255.255")); 22 | // Assert.assertFalse(JavaHost.isValidIp("255.255.255.256")); 23 | // Assert.assertFalse(JavaHost.isValidIp("255.255.255")); 24 | // Assert.assertFalse(JavaHost.isValidIp("255.255.255.")); 25 | } 26 | 27 | @Test 28 | public void updateVirtualDns() { 29 | JavaHost.queryIp("leopard.io"); 30 | 31 | Map map = new HashMap(); 32 | map.put("javahost1.leopard.io", "127.0.0.1"); 33 | map.put("javahost2.leopard.io", "127.0.0.2"); 34 | 35 | JavaHost.updateVirtualDns(map); 36 | List list = JavaHost.getDns().list(); 37 | for (Host host : list) { 38 | System.out.println(host); 39 | } 40 | Assert.assertEquals(2, list.size()); 41 | } 42 | 43 | } -------------------------------------------------------------------------------- /src/test/java/io/leopard/javahost/impl/DnsImplTest.java: -------------------------------------------------------------------------------- 1 | package io.leopard.javahost.impl; 2 | 3 | import io.leopard.javahost.JavaHost; 4 | import io.leopard.javahost.model.Host; 5 | 6 | import java.util.List; 7 | 8 | import org.junit.Assert; 9 | import org.junit.Test; 10 | 11 | public class DnsImplTest { 12 | 13 | private DnsImpl dns = new DnsImpl(); 14 | 15 | @Test 16 | public void update() { 17 | Assert.assertNull(JavaHost.queryIp("javahost.leopard.io")); 18 | dns.update("javahost.leopard.io", "127.0.0.1"); 19 | Assert.assertEquals("127.0.0.1", JavaHost.queryIp("javahost.leopard.io")); 20 | dns.remove("javahost.leopard.io"); 21 | Assert.assertNull(JavaHost.queryIp("javahost.leopard.io")); 22 | } 23 | 24 | @Test 25 | public void query() { 26 | 27 | { 28 | JavaHost.queryIp("leopard.io"); 29 | this.dns.query("leopard.io"); 30 | } 31 | { 32 | JavaHost.queryIp("baidu.com"); 33 | this.dns.query("baidu.com"); 34 | } 35 | { 36 | dns.update("javahost.leopard.io", "127.0.0.1"); 37 | JavaHost.queryIp("javahost.leopard.io"); 38 | this.dns.query("javahost.leopard.io"); 39 | } 40 | { 41 | JavaHost.queryIp("leopard2e.leopard.io"); 42 | this.dns.query("leopard2e.leopard.io"); 43 | } 44 | } 45 | 46 | @Test 47 | public void list() { 48 | dns.update("javahost.leopard.io", new String[] { "127.0.0.1", "127.0.0.2" }); 49 | List list = dns.list("javahost.leopard.io"); 50 | System.out.println("######虚拟DNS记录#######"); 51 | for (Host host : list) { 52 | System.out.println(host); 53 | } 54 | System.out.println("######ping#######"); 55 | for (int i = 0; i < 20; i++) { 56 | String ip = JavaHost.queryIp("javahost.leopard.io"); 57 | String ip2 = JavaHost.getIp("javahost.leopard.io"); 58 | System.out.println("ping host:javahost.leopard.io" + " 返回的ip:" + ip + " ip2:" + ip2); 59 | } 60 | } 61 | 62 | @Test 63 | public void test() { 64 | } 65 | 66 | } -------------------------------------------------------------------------------- /src/test/java/io/leopard/javahost/impl/HostsImplTest.java: -------------------------------------------------------------------------------- 1 | package io.leopard.javahost.impl; 2 | 3 | import io.leopard.javahost.model.Host; 4 | 5 | import java.util.List; 6 | 7 | import org.junit.Assert; 8 | import org.junit.Test; 9 | 10 | public class HostsImplTest { 11 | 12 | private HostsImpl hosts = new HostsImpl(); 13 | 14 | @Test 15 | public void list() { 16 | List list = hosts.list(); 17 | for (Host host : list) { 18 | System.out.println(host.toString()); 19 | } 20 | } 21 | 22 | @Test 23 | public void query() { 24 | Assert.assertEquals("112.126.75.27", hosts.query("leopard2e.leopard.io")); 25 | } 26 | 27 | @Test 28 | public void exist() { 29 | Assert.assertTrue(hosts.exist("leopard2e.leopard.io")); 30 | } 31 | 32 | } -------------------------------------------------------------------------------- /src/test/resources/test.txt: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | --------------------------------------------------------------------------------