1 /* |
|
2 * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved. |
|
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. |
|
4 * |
|
5 * This code is free software; you can redistribute it and/or modify it |
|
6 * under the terms of the GNU General Public License version 2 only, as |
|
7 * published by the Free Software Foundation. |
|
8 * |
|
9 * This code is distributed in the hope that it will be useful, but WITHOUT |
|
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
|
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License |
|
12 * version 2 for more details (a copy is included in the LICENSE file that |
|
13 * accompanied this code). |
|
14 * |
|
15 * You should have received a copy of the GNU General Public License version |
|
16 * 2 along with this work; if not, write to the Free Software Foundation, |
|
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. |
|
18 * |
|
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA |
|
20 * or visit www.oracle.com if you need additional information or have any |
|
21 * questions. |
|
22 */ |
|
23 |
|
24 /* |
|
25 */ |
|
26 |
|
27 import java.net.*; |
|
28 import java.util.*; |
|
29 import sun.net.spi.nameservice.*; |
|
30 |
|
31 |
|
32 public class SimpleNameService implements NameService { |
|
33 // host name <-> host addr mapping |
|
34 private HashMap<String, String> hosts = new LinkedHashMap<String, String>(); |
|
35 |
|
36 public void put(String host, String addr) { |
|
37 hosts.put(host, addr); |
|
38 } |
|
39 |
|
40 private static String addrToString(byte addr[]) { |
|
41 return Byte.toString(addr[0]) + "." + |
|
42 Byte.toString(addr[1]) + "." + |
|
43 Byte.toString(addr[2]) + "." + |
|
44 Byte.toString(addr[3]); |
|
45 } |
|
46 |
|
47 public SimpleNameService() { |
|
48 } |
|
49 |
|
50 public InetAddress[] lookupAllHostAddr(String host) throws UnknownHostException { |
|
51 String addr = hosts.get(host); |
|
52 if (addr == null) { |
|
53 throw new UnknownHostException(host); |
|
54 } |
|
55 |
|
56 StringTokenizer tokenizer = new StringTokenizer(addr, "."); |
|
57 byte addrs[] = new byte[4]; |
|
58 for (int i = 0; i < 4; i++) { |
|
59 addrs[i] = (byte)Integer.parseInt(tokenizer.nextToken()); |
|
60 } |
|
61 InetAddress[] ret = new InetAddress[1]; |
|
62 ret[0] = InetAddress.getByAddress(host, addrs); |
|
63 return ret; |
|
64 } |
|
65 |
|
66 public String getHostByAddr(byte[] addr) throws UnknownHostException { |
|
67 String addrString = addrToString(addr); |
|
68 Iterator i = hosts.keySet().iterator(); |
|
69 while (i.hasNext()) { |
|
70 String host = (String)i.next(); |
|
71 String value = (String)hosts.get(host); |
|
72 if (value.equals(addrString)) { |
|
73 return host; |
|
74 } |
|
75 } |
|
76 throw new UnknownHostException(); |
|
77 } |
|
78 } |
|