Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/test/sun/net/InetAddress/nameservice/simple/SimpleNameService.java
38862 views
/*1* Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/*24* A simple name service based on an in-memory HashMap.25*/26import java.net.UnknownHostException;27import java.net.InetAddress;28import sun.net.spi.nameservice.*;29import java.util.*;3031public final class SimpleNameService implements NameService {3233private static LinkedHashMap hosts = new LinkedHashMap();3435private static String addrToString(byte addr[]) {36return Byte.toString(addr[0]) + "." +37Byte.toString(addr[1]) + "." +38Byte.toString(addr[2]) + "." +39Byte.toString(addr[3]);40}4142// ------------4344public static void put(String host, String addr) {45hosts.put(host, addr);46}4748public static void put(String host, byte addr[]) {49hosts.put(host, addrToString(addr));50}5152public static void remove(String host) {53hosts.remove(host);54}5556public static int entries () {57return hosts.size();58}5960public static int lookupCalls() {61return lookupCalls;62}6364static int lookupCalls = 0;6566// ------------6768public SimpleNameService() throws Exception {69}7071public InetAddress[] lookupAllHostAddr(String host) throws UnknownHostException {7273lookupCalls ++;7475String value = (String)hosts.get(host);76if (value == null) {77throw new UnknownHostException(host);78}79StringTokenizer st = new StringTokenizer(value, ".");80byte addr[] = new byte[4];81for (int i=0; i<4; i++) {82addr[i] = (byte)Integer.parseInt(st.nextToken());83}84InetAddress[] res = new InetAddress[1];85res[0] = InetAddress.getByAddress(host, addr);86return res;87}8889public String getHostByAddr(byte[] addr) throws UnknownHostException {90String addrString = addrToString(addr);91Iterator i = hosts.keySet().iterator();92while (i.hasNext()) {93String host = (String)i.next();94String value = (String)hosts.get(host);95if (value.equals(addrString)) {96return host;97}98}99throw new UnknownHostException();100}101}102103104