undefect. CWE-407 — 63 sites patched across 27 ecosystems

Authors: russell@unturf.com · brackishbert@gmail.com · foxhop.net · TimeHexOn.com

Patches, unit tests, benchmarks, whitepaper, and outreach briefs.
Public domain — no copyright claimed. Use freely.
This commit is contained in:
russell@unturf.com 2026-03-26 17:11:57 -04:00
commit 0a580b313d
70422 changed files with 17213626 additions and 0 deletions

View file

@ -0,0 +1,84 @@
/*
* Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 5087907
* @summary InetAddress.getAllByName does not obey setting of java.net.preferIPv6Addresses
* @run main/othervm -Djava.net.preferIPv6Addresses=false B5087907
* @run main/othervm -Djava.net.preferIPv6Addresses=true B5087907
* @run main/othervm B5087907
*/
import java.net.*;
public class B5087907 {
public static void main(String args[]) {
InetAddress lh = null;
InetAddress addrs[] = null;
try {
lh = InetAddress.getByName("localhost");
addrs = InetAddress.getAllByName("localhost");
} catch (UnknownHostException e) {
System.out.println ("Cant lookup localhost. cant run test");
return;
}
boolean hasIPv4Address = false;
boolean hasIPv6Address = false;
for (InetAddress addr: addrs) {
if (addr instanceof Inet4Address) {
hasIPv4Address = true;
}
if (addr instanceof Inet6Address) {
hasIPv6Address = true;
}
if (hasIPv4Address && hasIPv6Address) {
break;
}
}
String prop = System.getProperty("java.net.preferIPv6Addresses");
boolean preferIPv6Addresses = (prop == null) ? false : prop.equals("true");
System.out.println("java.net.preferIPv6Addresses: " + preferIPv6Addresses);
System.out.println("localhost resolves to:");
for (InetAddress addr: addrs) {
System.out.println(" " + addr);
}
System.out.println("InetAddres.getByName returned: " + lh);
boolean failed = false;
if (preferIPv6Addresses && hasIPv6Address) {
if (!(lh instanceof Inet6Address)) failed = true;
}
if (!preferIPv6Addresses && hasIPv4Address) {
if (!(lh instanceof Inet4Address)) failed = true;
}
if (failed) {
throw new RuntimeException("Test failed!");
}
}
}

View file

@ -0,0 +1,43 @@
/*
* Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 6246242
* @summary UnknownHostException contains wrong error message
*/
import java.net.*;
public class B6246242 {
public static void main(String[] args) {
InetAddress a;
try {
a = InetAddress.getByName("foo.bar");
} catch (UnknownHostException e) {
String s = e.getMessage();
if (s.indexOf("foo.bar: foo.bar") >= 0)
throw new RuntimeException("UnknownHostException has wrong message: " + s);
}
}
}

View file

@ -0,0 +1,57 @@
/*
* Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 6296240
* @summary REGRESSION: InetAddress.getAllByName accepts badly formed address
*/
import java.net.*;
import java.util.BitSet;
public class B6296240 {
public static void main(String[] args) {
String[] malformedIPv4s = {"192.168.1.220..."};
BitSet expectedExceptions = new BitSet(malformedIPv4s.length);
expectedExceptions.clear();
for (int i = 0; i < malformedIPv4s.length; i++) {
try {
InetAddress.getAllByName(malformedIPv4s[i]);
} catch (UnknownHostException e) {
expectedExceptions.set(i);
}
}
for (int i = 0; i < malformedIPv4s.length; i++) {
if (!expectedExceptions.get(i)) {
System.out.println("getAllByName(\"" + malformedIPv4s[i] + "\") should throw exception.");
}
}
if (expectedExceptions.cardinality() != malformedIPv4s.length) {
throw new RuntimeException("Failed: some expected UnknownHostExceptions are not thrown.");
}
}
}

View file

@ -0,0 +1,95 @@
/*
* Copyright (c) 2001, 2002, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 4321350
* @bug 4516522
* @summary Check that InetAddress.getByName() throws UHE with dotted
* IP address with octets out of range (Windows specific bug)
* or when bad IPv6 Litterals addresses are passed.
*/
import java.net.InetAddress;
import java.net.UnknownHostException;
public class BadDottedIPAddress {
public static void main(String args[]) throws Exception {
String host = "999.999.999.999";
boolean exc_thrown = false;
try {
InetAddress ia = InetAddress.getByName(host);
} catch (UnknownHostException e) {
exc_thrown = true;
}
if (!exc_thrown) {
throw new Exception("UnknownHostException was not thrown for: "
+ host);
}
host = "[]";
exc_thrown = false;
try {
InetAddress ia = InetAddress.getByName(host);
} catch (UnknownHostException e) {
exc_thrown = true;
} catch (Exception e) {
}
if (!exc_thrown) {
throw new Exception("UnknownHostException was not thrown for: "
+ host);
}
host = "[127.0.0.1]";
exc_thrown = false;
try {
InetAddress ia = InetAddress.getByName(host);
} catch (UnknownHostException e) {
exc_thrown = true;
} catch (Exception e) {
}
if (!exc_thrown) {
throw new Exception("UnknownHostException was not thrown for: "
+ host);
}
host = "[localhost]";
exc_thrown = false;
try {
InetAddress ia = InetAddress.getByName(host);
} catch (UnknownHostException e) {
exc_thrown = true;
} catch (Exception e) {
}
if (!exc_thrown) {
throw new Exception("UnknownHostException was not thrown for: "
+ host);
}
}
}

View file

@ -0,0 +1,59 @@
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @author Gary Ellison
* @bug 4208282
* @summary java.net.InetAddress.getByName caching unknown host lookups
*/
import java.net.InetAddress;
public class CachedUnknownHostName {
public static void main(String argv[]) throws Exception {
String hostname = new String("bogusHostName");
try {
InetAddress.getByName(hostname);
System.err.println("Missing java.net.UnknownHostException for host " +
hostname);
throw new Exception("Missing java.net.UnknownHostException");
} catch(java.net.UnknownHostException e) {
// this one is anticipated
System.out.println("Caught expected exception:" + e);
}
try {
InetAddress.getByName(hostname);
System.err.println("Missing java.net.UnknownHostException for host " +
hostname);
throw new Exception("Missing java.net.UnknownHostException");
} catch(java.net.UnknownHostException e) {
// this is the one that was not firing off.
System.out.println("Caught expected exception:" + e);
}
System.out.println("Passed. OKAY");
}
}

View file

@ -0,0 +1,103 @@
/*
* Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4889870 4890033
* @summary java -Xcheck:jni failing in net code on Solaris / [Datagram]Socket.getLocalAddress() failure
* @library /test/lib
* @build jdk.test.lib.NetworkConfiguration
* jdk.test.lib.Platform
* @run main/othervm -Xcheck:jni CheckJNI
*/
import java.net.*;
import java.util.*;
import java.util.stream.Collectors;
import jdk.test.lib.NetworkConfiguration;
import jdk.test.lib.net.IPSupport;
public class CheckJNI {
public static void main (String[] args) throws Exception {
/* try to invoke as much java.net native code as possible */
InetAddress loopback = InetAddress.getLoopbackAddress();
System.out.println("Testing loopback Socket/ServerSocket");
testSocket(loopback);
System.out.println("Testing loopback DatagramSocket");
testDatagram(loopback);
if (IPSupport.hasIPv4()) {
InetAddress loopback4 = InetAddress.getByName("127.0.0.1");
System.out.println("Testing IPv4 Socket/ServerSocket");
testSocket(loopback4);
System.out.println("Testing IPv4 DatagramSocket");
testDatagram(loopback4);
}
/* Find link local IPv6 addrs to test */
List<Inet6Address> addrs = NetworkConfiguration.probe()
.ip6Addresses()
.filter(Inet6Address::isLinkLocalAddress)
.collect(Collectors.toList());
for (Inet6Address ia6 : addrs) {
System.out.println("Address:" + ia6);
System.out.println("Testing IPv6 Socket");
testSocket(ia6);
System.out.println("Testing IPv6 DatagramSocket");
testDatagram(ia6);
}
System.out.println("OK");
}
static void testSocket(InetAddress ia) throws Exception {
ServerSocket server = new ServerSocket(0, 0, ia);
Socket s = new Socket(ia, server.getLocalPort());
s.close();
server.close();
}
static void testDatagram(InetAddress ia) throws Exception {
DatagramSocket s1 = new DatagramSocket(0, ia);
DatagramSocket s2 = new DatagramSocket(0, ia);
System.out.println("s1: local address=" + s1.getLocalAddress()
+ ", local port=" + s1.getLocalPort());
System.out.println("s2: local address=" + s2.getLocalAddress()
+ ", local port=" + s2.getLocalPort());
DatagramPacket p1 = new DatagramPacket (
"hello world".getBytes(),
0, "hello world".length(), s2.getLocalAddress(),
s2.getLocalPort()
);
DatagramPacket p2 = new DatagramPacket(new byte[128], 128);
s1.send(p1);
s2.receive(p2);
s1.close();
s2.close();
}
}

View file

@ -0,0 +1,85 @@
/*
* Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 6376404 8201545
* @summary InetAddress needs a getLoopbackAddress
*/
import java.net.*;
public class GetLoopbackAddress
{
static InetAddress IPv4Loopback;
static InetAddress IPv6Loopback;
static {
try {
IPv4Loopback = InetAddress.getByAddress(
new byte[] {0x7F,0x00,0x00,0x01});
IPv6Loopback = InetAddress.getByAddress(
new byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01});
} catch (UnknownHostException e) {
}
}
public static void main(String[] args) throws Exception {
InetAddress addr = InetAddress.getLoopbackAddress();
if (!(addr.equals(IPv4Loopback) || addr.equals(IPv6Loopback))) {
throw new RuntimeException("Failed: getLoopbackAddress" +
" not returning a valid loopback address");
}
InetAddress addr2 = InetAddress.getLoopbackAddress();
if (addr != addr2) {
throw new RuntimeException("Failed: getLoopbackAddress" +
" should return a reference to the same InetAddress loopback instance.");
}
InetAddress addrFromNullHost = InetAddress.getByName(null);
if (!addrFromNullHost.isLoopbackAddress()) {
throw new RuntimeException("getByName(null) did not return a" +
" loopback address, but " + addrFromNullHost);
}
InetAddress addrFromEmptyHost = InetAddress.getByName("");
if (!addrFromEmptyHost.isLoopbackAddress()) {
throw new RuntimeException("getByName with a host of length == 0," +
" did not return a loopback address, but " + addrFromEmptyHost);
}
InetAddress[] addrsByNull = InetAddress.getAllByName(null);
if (!addrsByNull[0].isLoopbackAddress()) {
throw new RuntimeException("getAllByName(null) did not return" +
" a loopback address, but " + addrsByNull[0]);
}
InetAddress[] addrsByEmpty = InetAddress.getAllByName("");
if (!addrsByEmpty[0].isLoopbackAddress()) {
throw new RuntimeException("getAllByName with a host of length" +
" == 0, did not return a loopback address, but " + addrsByEmpty[0]);
}
}
}

View file

@ -0,0 +1,101 @@
/*
* Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 4687909
* @summary Check Inet6Address.hashCode returns a reasonable spread of hash
* codes.
* @key randomness
*/
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Random;
public class HashSpread {
static Random r = new Random();
/**
* Generate and return a random IPv6 address.
*/
static InetAddress randomIPv6Adress() {
StringBuffer sb = new StringBuffer();
for (int i=0; i<8; i++) {
if (i > 0)
sb.append(":");
for (int j=0; j<4; j++) {
int v = r.nextInt(16);
if (v < 10) {
sb.append(Integer.toString(v));
} else {
char c = (char) ('A' + v - 10);
sb.append(c);
}
}
}
try {
return InetAddress.getByName(sb.toString());
} catch (UnknownHostException x) {
throw new Error("Internal error in test");
}
}
public static void main(String args[]) throws Exception {
int iterations = 10000;
if (args.length > 0) {
iterations = Integer.parseInt(args[0]);
}
int MIN_SHORT = (int)Short.MIN_VALUE;
int MAX_SHORT = (int)Short.MAX_VALUE;
/*
* Iterate through 10k hash codes and count the number
* in the MIN_SHORT-MAX_SHORT range.
*/
int narrow = 0;
for (int i=0; i<iterations; i++) {
int hc = randomIPv6Adress().hashCode();
if (hc >= MIN_SHORT && hc <= MAX_SHORT) {
narrow++;
}
}
/*
* If >85% of hash codes in the range then fail.
*/
double percent = (double)narrow / (double)iterations * 100.0;
if (percent > 85.0) {
throw new RuntimeException(percent + " of hash codes were in " +
MIN_SHORT + " to " + MAX_SHORT + " range.");
}
}
}

View file

@ -0,0 +1,188 @@
/*
* Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import jdk.test.lib.net.IPSupport;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.testng.Assert;
/* @test
* @bug 8244958
* @library /test/lib
* @build jdk.test.lib.Platform jdk.test.lib.net.IPSupport
* @summary Test that "jdk.net.hosts.file" NameService implementation returns addresses
* with respect to "java.net.preferIPv4Stack" and "java.net.preferIPv6Addresses" system
* property values
* @run testng/othervm -Djdk.net.hosts.file=TestHostsFile.txt
* -Djava.net.preferIPv4Stack=true -Djava.net.preferIPv6Addresses=true HostsFileOrderingTest
* @run testng/othervm -Djdk.net.hosts.file=TestHostsFile.txt
* -Djava.net.preferIPv4Stack=true -Djava.net.preferIPv6Addresses=false HostsFileOrderingTest
* @run testng/othervm -Djdk.net.hosts.file=TestHostsFile.txt
* -Djava.net.preferIPv4Stack=true -Djava.net.preferIPv6Addresses=system HostsFileOrderingTest
* @run testng/othervm -Djdk.net.hosts.file=TestHostsFile.txt
* -Djava.net.preferIPv4Stack=true -Djava.net.preferIPv6Addresses=notVALID HostsFileOrderingTest
* @run testng/othervm -Djdk.net.hosts.file=TestHostsFile.txt
* -Djava.net.preferIPv4Stack=false -Djava.net.preferIPv6Addresses=true HostsFileOrderingTest
* @run testng/othervm -Djdk.net.hosts.file=TestHostsFile.txt
* -Djava.net.preferIPv4Stack=false -Djava.net.preferIPv6Addresses=false HostsFileOrderingTest
* @run testng/othervm -Djdk.net.hosts.file=TestHostsFile.txt
* -Djava.net.preferIPv4Stack=false -Djava.net.preferIPv6Addresses=system HostsFileOrderingTest
* @run testng/othervm -Djdk.net.hosts.file=TestHostsFile.txt
* -Djava.net.preferIPv4Stack=false -Djava.net.preferIPv6Addresses=notVALID HostsFileOrderingTest
* @run testng/othervm -Djdk.net.hosts.file=TestHostsFile.txt HostsFileOrderingTest
*/
public class HostsFileOrderingTest {
/*
* Generate hosts file with the predefined list of IP addresses
*/
@BeforeClass
public void generateHostsFile() throws Exception {
String content = ADDRESSES_LIST.stream()
.map(addr -> addr + " " + TEST_HOST_NAME)
.collect(
Collectors.joining(System.lineSeparator(),
"# Generated hosts file"+System.lineSeparator(),
System.lineSeparator())
);
Files.write(HOSTS_FILE_PATH, content.getBytes(StandardCharsets.UTF_8));
}
/*
* Test that HostsFile name service returns addresses in order that complies with the
* 'sun.net.preferIPv4Stack' and 'preferIPv6Addresses'
*/
@Test
public void testOrdering() throws Exception {
String [] resolvedAddresses = Arrays.stream(InetAddress.getAllByName("hostname.test.com"))
.map(InetAddress::getHostAddress).toArray(String[]::new);
String [] expectedAddresses = getExpectedAddressesArray();
if (Arrays.deepEquals(resolvedAddresses, expectedAddresses)) {
System.err.println("Test passed: The expected list of IP addresses is returned");
} else {
System.err.printf("Expected addresses:%n%s%n", Arrays.deepToString(expectedAddresses));
System.err.printf("Resolved addresses:%n%s%n", Arrays.deepToString(resolvedAddresses));
Assert.fail("Wrong host resolution result is returned");
}
}
/*
* Calculate expected order of IP addresses based on the "preferIPv6Addresses" and "preferIPv4Stack"
* system property values
*/
static ExpectedOrder getExpectedOrderFromSystemProperties() {
if (PREFER_IPV4_STACK_VALUE != null &&
PREFER_IPV4_STACK_VALUE.equalsIgnoreCase("true")) {
return ExpectedOrder.IPV4_ONLY;
}
if (!IPSupport.hasIPv6()) {
return ExpectedOrder.IPV4_ONLY;
}
if (PREFER_IPV6_ADDRESSES_VALUE != null) {
return switch(PREFER_IPV6_ADDRESSES_VALUE.toLowerCase()) {
case "true" -> ExpectedOrder.IPV6_IPV4;
case "system" -> ExpectedOrder.NO_MODIFICATION;
default -> ExpectedOrder.IPV4_IPV6;
};
}
return ExpectedOrder.IPV4_IPV6;
}
/*
* Return array expected to be returned by InetAddress::getAllByName call
*/
static String[] getExpectedAddressesArray() {
List<String> resList = switch (getExpectedOrderFromSystemProperties()) {
case IPV4_ONLY -> IPV4_LIST;
case IPV6_IPV4 -> IPV6_THEN_IPV4_LIST;
case IPV4_IPV6 -> IPV4_THEN_IPV6_LIST;
case NO_MODIFICATION -> ADDRESSES_LIST;
};
return resList.toArray(String[]::new);
}
// Possible types of addresses order
enum ExpectedOrder {
IPV4_ONLY,
IPV6_IPV4,
IPV4_IPV6,
NO_MODIFICATION;
}
// Addresses list
private static final List<String> ADDRESSES_LIST = List.of(
"192.168.239.11",
"2001:db8:85a3:0:0:8a2e:370:7334",
"192.168.14.10",
"2001:85a3:db8:0:0:8a2e:7334:370",
"192.168.129.16",
"2001:dead:beef:0:0:8a2e:1239:212"
);
// List of IPv4 addresses. The order is as in hosts file
private static final List<String> IPV4_LIST = ADDRESSES_LIST.stream()
.filter(ips -> ips.contains("."))
.collect(Collectors.toUnmodifiableList());
// List of IPv6 addresses. The order is as in hosts file
private static final List<String> IPV6_LIST = ADDRESSES_LIST.stream()
.filter(ip -> ip.contains(":"))
.collect(Collectors.toUnmodifiableList());
// List of IPv4 then IPv6 addresses. Orders inside each address type block is the same
// as in hosts file
private static final List<String> IPV4_THEN_IPV6_LIST = Stream.of(IPV4_LIST, IPV6_LIST)
.flatMap(Collection::stream).collect(Collectors.toList());
// List of IPv6 then IPv4 addresses. Orders inside each address type block is the same
// as in hosts file
private static final List<String> IPV6_THEN_IPV4_LIST = Stream.of(IPV6_LIST, IPV4_LIST)
.flatMap(Collection::stream).collect(Collectors.toList());
private static final String HOSTS_FILE_NAME = "TestHostsFile.txt";
private static final Path HOSTS_FILE_PATH = Paths.get(
System.getProperty("user.dir", ".")).resolve(HOSTS_FILE_NAME);
private static final String TEST_HOST_NAME = "hostname.test.com";
private static final String PREFER_IPV6_ADDRESSES_VALUE =
System.getProperty("java.net.preferIPv6Addresses");
private static final String PREFER_IPV4_STACK_VALUE =
System.getProperty("java.net.preferIPv4Stack");
}

View file

@ -0,0 +1,64 @@
/*
* Copyright (c) 2003, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 4866927
* @summary InetAddress.getByName behaves differently on windows
*/
import java.net.*;
public class IPv4Formats {
public static void main(String[] args) {
InetAddress ad1, ad2;
String adds[][] = {
{"0", "0.0.0.0"},
{"126.1", "126.0.0.1"},
{"128.50.65534", "128.50.255.254"},
{"192.168.1.2", "192.168.1.2"},
{"invalidhost.invalid", null},
{"1024.1.2.3", null},
{"128.14.66000", null }
};
for (int i = 0; i < adds.length; i++) {
if (adds[i][1] != null) {
try {
ad1 = InetAddress.getByName(adds[i][0]);
ad2 = InetAddress.getByName(adds[i][1]);
} catch (UnknownHostException ue) {
throw new RuntimeException("Wrong conversion: " + adds[i][0] + " should be " + adds[i][1] + " But throws " + ue);
}
if (! ad1.equals(ad2))
throw new RuntimeException("Wrong conversion: " + adds[i][0] + " should be " + adds[i][1] + " But is " + ad1);
} else {
try {
ad1 = InetAddress.getByName(adds[i][0]);
// should throw an UnknownHostException
throw new RuntimeException(adds[i][0] + " should throw UnknownHostException!");
} catch (UnknownHostException e) {
// This is what we expect!
}
}
}
}
}

View file

@ -0,0 +1,227 @@
/*
* Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 8134577
* @summary Test the internal NameService implementation which is enabled via
* the system property jdk.net.hosts.file. This property specifies
* a file name that contains address host mappings, similar to those in
* /etc/hosts file.
* @library /test/lib
* @build jdk.test.lib.net.IPSupport
* @run main/othervm -Djdk.net.hosts.file=TestHosts -Dsun.net.inetaddr.ttl=0
* InternalNameServiceTest
*/
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import jdk.test.lib.net.IPSupport;
public class InternalNameServiceTest {
static final String HOSTS_FILE_NAME = System.getProperty("jdk.net.hosts.file");
public static void main(String args[]) throws Exception {
testHostToIPAddressMappings(HOSTS_FILE_NAME);
testIpAddressToHostNameMappings(HOSTS_FILE_NAME);
}
private static void testHostToIPAddressMappings(String hostsFileName)
throws Exception, UnknownHostException {
System.out.println(" TEST HOST TO IP ADDRESS MAPPINGS ");
InetAddress testAddress;
byte[] retrievedIpAddr;
byte[] expectedIpAddr1 = { 1, 2, 3, 4 };
byte[] expectedIpAddr2 = { 5, 6, 7, 8 };
byte[] expectedIpAddrIpv6_1 = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
// hosts file with
// # test hosts file for internal NameService
// 1.2.3.4 host.sample-domain
// 5.6.7.8 host1.sample-domain
// 1.2.3.4 host2.sample-domain # this is a comment
// host3.sample-domain # no ip address
// host4.sample-domain # space as ip address
// host5.sample-domain # double space as ip address
// add comment to hosts file
addMappingToHostsFile("test hosts file for internal NameService ", "#", hostsFileName,
false);
addMappingToHostsFile("host.sample-domain", "1.2.3.4", hostsFileName,
true);
testAddress = InetAddress.getByName("host.sample-domain");
retrievedIpAddr = testAddress.getAddress();
if (!Arrays.equals(retrievedIpAddr, expectedIpAddr1)) {
throw new RuntimeException(
"retrievedIpAddr not equal to expectedipAddr");
}
addMappingToHostsFile("host1.sample-domain", "5.6.7.8", hostsFileName,
true);
addMappingToHostsFile("host2.sample-domain", "1.2.3.4", hostsFileName,
true);
testAddress = InetAddress.getByName("host1.sample-domain");
retrievedIpAddr = testAddress.getAddress();
if (!Arrays.equals(retrievedIpAddr, expectedIpAddr2)) {
throw new RuntimeException(
"retrievedIpAddr not equal to expectedIpAddr");
}
testAddress = InetAddress.getByName("host2.sample-domain");
retrievedIpAddr = testAddress.getAddress();
if (!Arrays.equals(retrievedIpAddr, expectedIpAddr1)) {
throw new RuntimeException(
"retrievedIpAddr not equal to expectedIpAddr");
}
try {
addMappingToHostsFile("host3.sample-domain", "", hostsFileName,
true);
testAddress = InetAddress.getByName("host3.sample-domain");
throw new RuntimeException(
"Expected UnknownHostException not thrown");
} catch (UnknownHostException uhEx) {
System.out.println("UnknownHostException as expected for host host3.sample-domain");
}
try {
addMappingToHostsFile("host4.sample-domain", " ", hostsFileName,
true);
testAddress = InetAddress.getByName("host4.sample-domain");
throw new RuntimeException(
"Expected UnknownHostException not thrown");
} catch (UnknownHostException uhEx) {
System.out.println("UnknownHostException as expected for host host4.sample-domain");
}
try {
addMappingToHostsFile("host5.sample-domain", " ", hostsFileName,
true);
testAddress = InetAddress.getByName("host4.sample-domain");
throw new RuntimeException(
"Expected UnknownHostException not thrown");
} catch (UnknownHostException uhEx) {
System.out.println("UnknownHostException as expected for host host5.sample-domain");
}
// IPV6 tests
if (IPSupport.hasIPv6()) {
addMappingToHostsFile("host-ipv6.sample-domain", "::1", hostsFileName, true);
testAddress = InetAddress.getByName("host-ipv6.sample-domain");
retrievedIpAddr = testAddress.getAddress();
if (!Arrays.equals(retrievedIpAddr, expectedIpAddrIpv6_1)) {
System.out.println("retrieved ipv6 addr == " + Arrays.toString(retrievedIpAddr));
System.out.println("expected ipv6 addr == " + Arrays.toString(expectedIpAddrIpv6_1));
throw new RuntimeException(
"retrieved IPV6 Addr not equal to expected IPV6 Addr");
}
}
}
private static void testIpAddressToHostNameMappings(String hostsFileName)
throws Exception {
System.out.println(" TEST IP ADDRESS TO HOST MAPPINGS ");
InetAddress testAddress;
String retrievedHost;
String expectedHost = "testHost.testDomain";
byte[] testHostIpAddr = { 10, 2, 3, 4 };
byte[] testHostIpAddr2 = { 10, 5, 6, 7 };
byte[] testHostIpAddr3 = { 10, 8, 9, 10 };
byte[] testHostIpAddr4 = { 10, 8, 9, 11 };
// add comment to hosts file
addMappingToHostsFile("test hosts file for internal NameService ", "#", hostsFileName,
false);
addMappingToHostsFile("testHost.testDomain", "10.2.3.4", hostsFileName,
true);
testAddress = InetAddress.getByAddress(testHostIpAddr);
System.out.println("******* testAddress == " + testAddress);
retrievedHost = testAddress.getHostName();
if (!expectedHost.equals(retrievedHost)) {
throw new RuntimeException(
"retrieved host name not equal to expected host name");
}
addMappingToHostsFile("testHost.testDomain", "10.5.6.7", hostsFileName,
true);
testAddress = InetAddress.getByAddress(testHostIpAddr2);
System.out.println("******* testAddress == " + testAddress);
retrievedHost = testAddress.getHostName();
System.out.println("******* retrievedHost == " + retrievedHost);
if (!expectedHost.equals(retrievedHost)) {
throw new RuntimeException("retrieved host name " + retrievedHost
+ " not equal to expected host name" + expectedHost);
}
testAddress = InetAddress.getByAddress(testHostIpAddr4);
System.out.println("******* testAddress == " + testAddress);
if ("10.8.9.11".equalsIgnoreCase(testAddress.getCanonicalHostName())) {
System.out.println("addr = " + addrToString(testHostIpAddr4)
+ " resolve to a host address as expected");
} else {
System.out.println("addr = " + addrToString(testHostIpAddr4)
+ " does not resolve as expected, testAddress == " + testAddress.getCanonicalHostName());
throw new RuntimeException("problem with resolving "
+ addrToString(testHostIpAddr4));
}
try {
addMappingToHostsFile("", "10.8.9.10", hostsFileName, true);
testAddress = InetAddress.getByAddress(testHostIpAddr3);
System.out.println("******* testAddress == " + testAddress);
retrievedHost = testAddress.getCanonicalHostName();
} catch (Throwable t) {
throw new RuntimeException("problem with resolving "
+ addrToString(testHostIpAddr3));
}
}
private static String addrToString(byte addr[]) {
return Byte.toString(addr[0]) + "." + Byte.toString(addr[1]) + "."
+ Byte.toString(addr[2]) + "." + Byte.toString(addr[3]);
}
private static void addMappingToHostsFile( String host,
String addr,
String hostsFileName,
boolean append)
throws Exception {
String mapping = addr + " " + host;
try (PrintWriter hfPWriter = new PrintWriter(new BufferedWriter(
new FileWriter(hostsFileName, append)))) {
hfPWriter.println(mapping);
}
}
}

View file

@ -0,0 +1,120 @@
/*
* Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 8134577
* @summary Test the internal NameService implementation which is enabled via
* the system property jdk.net.hosts.file. This property specifies
* a file name that contains address host mappings, similar to those in
* /etc/hosts file. TestHosts-III file exist, with a set of ipv4 and ipv6
* mappings
* @library /test/lib
* @build jdk.test.lib.net.IPSupport
* @run main/othervm -Djdk.net.hosts.file=${test.src}/TestHosts-III -Dsun.net.inetaddr.ttl=0
* InternalNameServiceWithHostsFileTest
*/
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import jdk.test.lib.net.IPSupport;
public class InternalNameServiceWithHostsFileTest {
public static void main(String args[]) throws Exception {
// fe80::1
byte[] expectedIpv6Address = { (byte) 0xfe, (byte) 0x80, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 1 };
// fe00::0
byte[] expectedIpv6LocalAddress = { (byte) 0xfe, (byte) 0x00, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
// 10.2.3.4
byte[] expectedIpv4Address = { 10, 2, 3, 4 };
//
byte[] expectedIpv6LocalhostAddress = { 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 1 };
// 10.2.3.4 testHost.testDomain
testHostsMapping(expectedIpv4Address, "testHost.testDomain");
if (IPSupport.hasIPv6()) {
// ::1 ip6-localhost ip6-loopback
testHostsMapping(expectedIpv6LocalhostAddress, "ip6-localhost");
// fe00::0 ip6-localnet
testHostsMapping(expectedIpv6LocalAddress, "ip6-localnet");
// fe80::1 link-local-host
testHostsMapping(expectedIpv6Address, "link-local-host");
}
testReverseLookup("10.2.3.4", "testHost.testDomain");
if (IPSupport.hasIPv6()) {
testReverseLookup("::1", "ip6-localhost");
testReverseLookup("0:0:0:0:0:0:0:1", "ip6-localhost");
testReverseLookup("0000:0000:0000:0000:0000:0000:0000:0001", "ip6-localhost");
testReverseLookup("fe00::0", "ip6-localnet");
testReverseLookup("fe00:0:0:0:0:0:0:0", "ip6-localnet");
testReverseLookup("fe00:0000:0000:0000:0000:0000:0000:0000", "ip6-localnet");
testReverseLookup("fe80::1", "link-local-host");
testReverseLookup("fe80:000:0:00:0:000:00:1", "link-local-host");
testReverseLookup("fe80:0000:0000:0000:0000:0000:0000:0001", "link-local-host");
}
}
private static void testHostsMapping(byte[] expectedIpAddress, String hostName)
throws UnknownHostException {
InetAddress testAddress;
byte[] rawIpAddress;
testAddress = InetAddress.getByName(hostName);
System.out
.println("############################ InetAddress == "
+ testAddress);
rawIpAddress = testAddress.getAddress();
if (!Arrays.equals(rawIpAddress, expectedIpAddress)) {
System.out.println("retrieved address == "
+ Arrays.toString(rawIpAddress)
+ " not equal to expected address == "
+ Arrays.toString(expectedIpAddress));
throw new RuntimeException(
"retrieved address not equal to expected address");
}
System.out.println("retrieved address == "
+ Arrays.toString(rawIpAddress)
+ " equal to expected address == "
+ Arrays.toString(expectedIpAddress));
}
private static void testReverseLookup(String numericHost, String expectedName)
throws UnknownHostException {
String lookupResult = InetAddress.getByName(numericHost).getHostName();
if (!expectedName.equals(lookupResult)) {
throw new RuntimeException(
String.format(
"reverse lookup of \"%s\" is \"%s\", should be \"%s\"\n",
numericHost, lookupResult, expectedName));
}
}
}

View file

@ -0,0 +1,52 @@
/*
* Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 8134577
* @summary Test the internal NameService implementation which is enabled via
* the system property jdk.net.hosts.file. This property specifies
* a file name that contains address host mappings, similar to those in
* /etc/hosts file. TestHosts-II file doesn't exist, so a UHE should be
* thrown
* @run main/othervm -Djdk.net.hosts.file=TestHosts-II -Dsun.net.inetaddr.ttl=0
* InternalNameServiceWithNoHostsFileTest
*/
import java.net.InetAddress;
import java.net.UnknownHostException;
public class InternalNameServiceWithNoHostsFileTest {
public static void main(String args[]) throws Exception {
InetAddress testAddress = null;
try {
testAddress = InetAddress.getByName("host.sample-domain");
throw new RuntimeException ("UnknownHostException expected");
} catch (UnknownHostException uhEx) {
System.out.println("UHE caught as expected == " + uhEx.getMessage());
}
}
}

View file

@ -0,0 +1,55 @@
/*
* Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 4922568 8133015
* @run main/othervm -Djava.net.preferIPv4Stack=true IsHostReachableBug
* @summary isReachable returns true for IPv6
*/
import java.net.*;
import java.io.*;
public class IsHostReachableBug {
public static void main(String[] args) throws Exception{
String hostName = "fec0::1:a00:20ff:feed:b08d";
BufferedReader in = null;
FileWriter fw = null;
String inString = " ";
if (args.length > 0)
hostName = args[0];
InetAddress addr = InetAddress.getByName(hostName);
System.out.println("InetAddress is : " + addr);
System.out.println("Is InetAddress instance of Inet6Address ? "
+ (addr instanceof Inet6Address));
if (!addr.isReachable(10000)){
System.out.println(hostName + " is not reachable");
}else {
throw new RuntimeException ("IPv6 address should not be reachable");
}
}
}

View file

@ -0,0 +1,48 @@
/*
* Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 4639861 8133015
* @summary API to test reachability of a host
*/
import java.net.InetAddress;
import java.io.IOException;
import java.net.NetworkInterface;
public class IsReachable {
public static void main(String[] args) {
try {
InetAddress addr = InetAddress.getByName("localhost");
if (!addr.isReachable(10000))
throw new RuntimeException("Localhost should always be reachable");
NetworkInterface inf = NetworkInterface.getByInetAddress(addr);
if (inf != null) {
if (!addr.isReachable(inf, 20, 10000))
throw new RuntimeException("Localhost should always be reachable");
}
} catch (IOException e) {
throw new RuntimeException("Unexpected exception:" + e);
}
}
}

View file

@ -0,0 +1,65 @@
/*
* Copyright (c) 2015, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
/**
* @test
* @bug 8135305
* @key intermittent
* @library /test/lib
* @summary ensure we can't ping external hosts via loopback if
* @run main IsReachableViaLoopbackTest
*/
public class IsReachableViaLoopbackTest {
public static void main(String[] args) {
try {
InetAddress addr = InetAddress.getLoopbackAddress();
InetAddress remoteAddr = InetAddress.getByName("23.197.138.208"); // use literal address to avoid DNS checks
if (!addr.isReachable(10000))
throw new RuntimeException("Localhost should always be reachable");
NetworkInterface inf = NetworkInterface.getByInetAddress(addr);
if (inf != null) {
if (!addr.isReachable(inf, 20, 10000)) {
throw new RuntimeException("Localhost should always be reachable");
} else {
System.out.println(addr + " is reachable");
}
if (remoteAddr.isReachable(inf, 20, 10000)) {
throw new RuntimeException(remoteAddr + " is reachable");
} else {
System.out.println(remoteAddr + " is NOT reachable");
}
} else {
System.out.println("inf == null");
}
} catch (IOException e) {
throw new RuntimeException("Unexpected exception:" + e);
}
System.out.println("IsReachableViaLoopbackTest EXIT");
}
}

View file

@ -0,0 +1,61 @@
/*
* Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.security.Principal;
public class MyPrincipal implements Principal {
private String name;
public MyPrincipal(String name) {
if (name == null)
throw new NullPointerException("illegal null input");
this.name = name;
}
public String getName() {
return name;
}
public String toString() {
return("MyPrincipal: " + name);
}
public boolean equals(Object o) {
if (o == null)
return false;
if (this == o)
return true;
if (!(o instanceof MyPrincipal))
return false;
MyPrincipal that = (MyPrincipal)o;
if (this.getName().equals(that.getName()))
return true;
return false;
}
public int hashCode() {
return name.hashCode();
}
}

View file

@ -0,0 +1,34 @@
/*
* Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8300038
* @modules java.base/java.net
* @compile/module=java.base java/net/NullCharInHostname.java
* @summary Make new version of JNU_GetStringPlatformChars which checks for null characters
* @run main/othervm java.base/java.net.NullCharInHostname
* @run main/othervm -Dfile.encoding=COMPAT java.base/java.net.NullCharInHostname
*/
public class NullCharInHostnameDriver { }

View file

@ -0,0 +1,445 @@
/*
* Copyright (c) 2023, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 8272215 8315767 8332686
* @summary Test for ofLiteral, ofPosixLiteral APIs in InetAddress classes
* @run junit/othervm -Djdk.net.hosts.file=nonExistingHostsFile.txt
* OfLiteralTest
* @run junit/othervm -Djdk.net.hosts.file=nonExistingHostsFile.txt
* -Djava.net.preferIPv4Stack=true
* OfLiteralTest
* @run junit/othervm -Djdk.net.hosts.file=nonExistingHostsFile.txt
* -Djava.net.preferIPv6Addresses=true
* OfLiteralTest
* @run junit/othervm -Djdk.net.hosts.file=nonExistingHostsFile.txt
* -Djava.net.preferIPv6Addresses=false
* OfLiteralTest
*/
import org.junit.Assert;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.function.Executable;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.MethodSource;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertThrows;
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class OfLiteralTest {
@ParameterizedTest
@MethodSource("validLiteralArguments")
public void validLiteral(InetAddressClass inetAddressClass,
String addressLiteral,
byte[] expectedAddressBytes) throws Exception {
InetAddress ofLiteralResult = switch (inetAddressClass) {
case INET_ADDRESS -> InetAddress.ofLiteral(addressLiteral);
case INET4_ADDRESS -> Inet4Address.ofLiteral(addressLiteral);
case INET4_ADDRESS_POSIX -> Inet4Address.ofPosixLiteral(addressLiteral);
case INET6_ADDRESS -> Inet6Address.ofLiteral(addressLiteral);
};
Assert.assertArrayEquals(expectedAddressBytes, ofLiteralResult.getAddress());
// POSIX literals are not compatible with InetAddress.getByName()
if (inetAddressClass != InetAddressClass.INET4_ADDRESS_POSIX) {
InetAddress getByNameResult = InetAddress.getByName(addressLiteral);
Assert.assertEquals(getByNameResult, ofLiteralResult);
}
}
private static Stream<Arguments> validLiteralArguments() throws Exception {
// 1080:0:0:0:8:800:200C:417A address bytes
byte[] ipv6AddressExpBytes = new byte[]{16, -128, 0, 0, 0, 0, 0, 0, 0,
8, 8, 0, 32, 12, 65, 122};
// ::129.144.52.38 address bytes
byte[] ipv4CompIpv6ExpBytes = new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, -127, -112, 52, 38};
// 222.173.190.239 address bytes
byte[] ipv4ExpBytes = new byte[]{(byte) 222, (byte) 173,
(byte) 190, (byte) 239};
// 222.173.190.39 address bytes
byte[] ipv4ExpBytes2 = new byte[]{(byte) 222, (byte) 173,
(byte) 190, 39};
// 1.2.3.4 address bytes
byte[] oneToFourAddressExpBytes = new byte[]{1, 2, 3, 4};
// 6.7.8.9 address bytes
byte[] sixtoNineAddressExpBytes = new byte[]{6, 7, 8, 9};
// ::FFFF:129.144.52.38 address bytes
byte[] ipv6Ipv4MappedAddressExpBytes = new byte[]{
(byte) 129, (byte) 144, 52, 38};
// 87.0.0.1 address bytes
byte[] ipv4_87_0_0_1 = new byte[]{87, 0, 0, 1};
// 127.0.0.1 address bytes
byte[] ipv4_127_0_0_1 = new byte[]{127, 0, 0, 1};
// 17.99.141.27 address bytes
byte[] ipv4_17_99_141_27 = new byte[]{17, 99, (byte)141, 27};
// 127.8.0.1 address bytes
byte[] ipv4_127_8_0_1 = new byte[]{127, 8, 0, 1};
// 0.0.0.42 address bytes
byte[] ipv4_0_0_0_42 = new byte[]{0, 0, 0, 42};
// 0.0.0.34 address bytes
byte[] ipv4_0_0_0_34 = new byte[]{0, 0, 0, 34};
// 127.0.1.2 address bytes
byte[] ipv4_127_0_1_2 = new byte[]{127, 0, 1, 2};
// 127.1.2.3 address bytes
byte[] ipv4_127_1_2_3 = new byte[]{127, 1, 2, 3};
// 255.255.255.255 address bytes
byte[] ipv4_255_255_255_255 = new byte[]{(byte)255, (byte)255, (byte)255, (byte)255};
Stream<Arguments> validLiterals = Stream.of(
// IPv6 address literals are parsable by Inet6Address.ofLiteral
// and InetAddress.ofLiteral methods
Arguments.of(InetAddressClass.INET6_ADDRESS,
"1080:0:0:0:8:800:200C:417A", ipv6AddressExpBytes),
Arguments.of(InetAddressClass.INET_ADDRESS,
"[1080:0:0:0:8:800:200C:417A]", ipv6AddressExpBytes),
// Compressed series of zeros with square brackets
Arguments.of(InetAddressClass.INET6_ADDRESS,
"[1080::8:800:200C:417A]", ipv6AddressExpBytes),
// Compressed series of zeros without square brackets
Arguments.of(InetAddressClass.INET_ADDRESS,
"1080::8:800:200C:417A", ipv6AddressExpBytes),
// IPv4-mapped IPv6 address literals are parsable by
// InetAddress.ofLiteral and Inet6Address.ofLiteral methods
Arguments.of(InetAddressClass.INET_ADDRESS,
"::FFFF:129.144.52.38", ipv6Ipv4MappedAddressExpBytes),
Arguments.of(InetAddressClass.INET_ADDRESS,
"[::ffff:1.2.3.4]", oneToFourAddressExpBytes),
Arguments.of(InetAddressClass.INET6_ADDRESS,
"::FFFF:129.144.52.38", ipv6Ipv4MappedAddressExpBytes),
Arguments.of(InetAddressClass.INET6_ADDRESS,
"[::ffff:1.2.3.4]", oneToFourAddressExpBytes),
// IPv4-compatible IPv6 address literals are parsable by
// Inet6Address.ofLiteral and InetAddress.ofLiteral methods
Arguments.of(InetAddressClass.INET6_ADDRESS,
"::129.144.52.38", ipv4CompIpv6ExpBytes),
Arguments.of(InetAddressClass.INET6_ADDRESS,
"[::129.144.52.38]", ipv4CompIpv6ExpBytes),
Arguments.of(InetAddressClass.INET_ADDRESS,
"::129.144.52.38", ipv4CompIpv6ExpBytes),
Arguments.of(InetAddressClass.INET_ADDRESS,
"[::129.144.52.38]", ipv4CompIpv6ExpBytes),
// Tests for IPv4 address literal forms
// form:'d.d.d.d' method:Inet4Address.ofLiteral
Arguments.of(InetAddressClass.INET4_ADDRESS,
"222.173.190.239", ipv4ExpBytes),
// form:'d.d.d.d' with decimal octet with leading zero
Arguments.of(InetAddressClass.INET4_ADDRESS,
"222.173.190.039", ipv4ExpBytes2),
Arguments.of(InetAddressClass.INET4_ADDRESS,
"06.07.08.09", sixtoNineAddressExpBytes),
// form:'d.d.d.d' method:InetAddress.ofLiteral
Arguments.of(InetAddressClass.INET_ADDRESS,
"222.173.190.239", ipv4ExpBytes),
// form:'d.d.d' method:Inet4Address.ofLiteral
Arguments.of(InetAddressClass.INET4_ADDRESS,
"222.173.48879", ipv4ExpBytes),
// form:'d.d.d' method:InetAddress.ofLiteral
Arguments.of(InetAddressClass.INET_ADDRESS,
"222.173.48879", ipv4ExpBytes),
// form:'d.d' method:Inet4Address.ofLiteral
Arguments.of(InetAddressClass.INET4_ADDRESS,
"222.11386607", ipv4ExpBytes),
// form:'d.d' method:InetAddress.ofLiteral
Arguments.of(InetAddressClass.INET_ADDRESS,
"222.11386607", ipv4ExpBytes),
// form:'d' method:Inet4Address.ofLiteral
Arguments.of(InetAddressClass.INET4_ADDRESS,
"3735928559", ipv4ExpBytes),
// form:'d' method:InetAddress.ofLiteral
Arguments.of(InetAddressClass.INET_ADDRESS,
"3735928559", ipv4ExpBytes),
// form:'d' method:InetAddress.ofLiteral -
// with leading 0 that is discarded and address
// parsed as decimal
Arguments.of(InetAddressClass.INET_ADDRESS,
"03735928559", ipv4ExpBytes),
// form:'x.x.x.x' method:InetAddress.ofPosixLiteral -
// with leading 0 treated as octal segment prefix
Arguments.of(InetAddressClass.INET4_ADDRESS_POSIX,
"0127.0.0.1", ipv4_87_0_0_1),
// form:'x.x.x.x' method:InetAddress.ofPosixLiteral -
// with leading 0 treated as octal segment prefix
Arguments.of(InetAddressClass.INET4_ADDRESS_POSIX,
"0177.0.0.1", ipv4_127_0_0_1),
// form:'x.x.x.x' method:InetAddress.ofPosixLiteral -
// with leading 0s treated as octal segment prefixes
Arguments.of(InetAddressClass.INET4_ADDRESS_POSIX,
"0177.0000.0000.0001", ipv4_127_0_0_1),
// form:'x.x.x.x' method:InetAddress.ofPosixLiteral -
// with leading 0 treated as octal segment prefix
Arguments.of(InetAddressClass.INET4_ADDRESS_POSIX,
"127.010.0.1", ipv4_127_8_0_1),
// form:'x.x.x.x' method:InetAddress.ofPosixLiteral -
// with leading 0 treated as octal segment prefix
Arguments.of(InetAddressClass.INET4_ADDRESS_POSIX,
"0377.0377.0377.0377", ipv4_255_255_255_255),
// form:'x.x.x' method:InetAddress.ofPosixLiteral -
// with leading 0s treated as octal segment prefixes
Arguments.of(InetAddressClass.INET4_ADDRESS_POSIX,
"0177.0.0402", ipv4_127_0_1_2),
// form:'x.x.x' method:InetAddress.ofPosixLiteral -
// with leading 0x treated as hexadecimal segment prefixes
Arguments.of(InetAddressClass.INET4_ADDRESS_POSIX,
"0x7F.0.0x102", ipv4_127_0_1_2),
// form:'x.x' method:InetAddress.ofPosixLiteral -
// with leading 0s treated as octal segment prefixes
Arguments.of(InetAddressClass.INET4_ADDRESS_POSIX,
"0177.0201003", ipv4_127_1_2_3),
// form:'x.x' method:InetAddress.ofPosixLiteral -
// with leading 0x treated as hexadecimal prefixes
Arguments.of(InetAddressClass.INET4_ADDRESS_POSIX,
"0x7F.0x10203", ipv4_127_1_2_3),
// form:'x.x' method:InetAddress.ofPosixLiteral -
// without prefixes treated as decimal
Arguments.of(InetAddressClass.INET4_ADDRESS_POSIX,
"127.66051", ipv4_127_1_2_3),
// form:'x' method:InetAddress.ofPosixLiteral -
// with leading 0 treated as octal segment prefix
Arguments.of(InetAddressClass.INET4_ADDRESS_POSIX,
"017700000001", ipv4_127_0_0_1),
// form:'x' method:InetAddress.ofPosixLiteral -
// with leading 0 treated as octal segment prefix
Arguments.of(InetAddressClass.INET4_ADDRESS_POSIX,
"02130706433", ipv4_17_99_141_27),
// form:'x' method:InetAddress.ofPosixLiteral -
// with leading 0 treated as octal segment prefix
Arguments.of(InetAddressClass.INET4_ADDRESS_POSIX,
"037777777777", ipv4_255_255_255_255),
// form:'x' method:InetAddress.ofPosixLiteral -
// with leading 0x treated as hex prefix
Arguments.of(InetAddressClass.INET4_ADDRESS_POSIX,
"0x1020304", oneToFourAddressExpBytes),
// form:'x' method:InetAddress.ofPosixLiteral -
// with leading 0x treated as hex prefix
Arguments.of(InetAddressClass.INET4_ADDRESS_POSIX,
"0xFFFFFFFF", ipv4_255_255_255_255),
// form:'x' method:InetAddress.ofPosixLiteral -
// without leading 0 treated as decimal
Arguments.of(InetAddressClass.INET4_ADDRESS_POSIX,
"2130706433", ipv4_127_0_0_1),
// form:'x' method:InetAddress.ofPosixLiteral -
// without leading 0 treated as decimal
Arguments.of(InetAddressClass.INET4_ADDRESS_POSIX,
"42", ipv4_0_0_0_42),
// form:'x' method:InetAddress.ofPosixLiteral -
// with leading 0 treated as octal segment prefix
Arguments.of(InetAddressClass.INET4_ADDRESS_POSIX,
"0100401404", oneToFourAddressExpBytes),
// form:'x' method:InetAddress.ofPosixLiteral -
// without prefixes treated as decimal
Arguments.of(InetAddressClass.INET4_ADDRESS_POSIX,
"16909060", oneToFourAddressExpBytes),
// form:'x' method:InetAddress.ofPosixLiteral -
// with leading 0 treated as octal segment prefix
Arguments.of(InetAddressClass.INET4_ADDRESS_POSIX,
"042", ipv4_0_0_0_34)
);
// Generate addresses for loopback and wildcard address test cases
var loopbackAndWildcardAddresses = List.of(
// Loopback address
InetAddress.getLoopbackAddress(),
// IPv6 wildcard address
InetAddress.getByName("::"),
// IPv4 wildcard address
InetAddress.getByName("0.0.0.0"));
// Get addresses for all network interfaces available,
// and construct a test case for each. And then combine
// them with loopback/wildcard test cases.
Stream<Arguments> hostAddressArguments = Stream.concat(
NetworkInterface.networkInterfaces()
.flatMap(NetworkInterface::inetAddresses),
loopbackAndWildcardAddresses.stream())
.flatMap(OfLiteralTest::addressToValidTestCases);
return Stream.concat(validLiterals, hostAddressArguments);
}
@ParameterizedTest
@MethodSource("invalidLiteralArguments")
public void invalidLiteral(InetAddressClass inetAddressClass,
String addressLiteral) {
var executable = constructExecutable(inetAddressClass, addressLiteral);
var exception = assertThrows(IllegalArgumentException.class, executable);
System.err.println("Expected exception observed: " + exception);
}
@ParameterizedTest
@EnumSource(InetAddressClass.class)
public void nullLiteral(InetAddressClass inetAddressClass) {
var executable = constructExecutable(inetAddressClass, null);
assertThrows(NullPointerException.class, executable);
}
private static Stream<Arguments> invalidLiteralArguments() {
Stream<Arguments> argumentsStream = Stream.of(
// IPv4 address wrapped in square brackets
Arguments.of(InetAddressClass.INET_ADDRESS, "[1.2.3.4]"),
Arguments.of(InetAddressClass.INET4_ADDRESS, "[1.2.3.4]"),
Arguments.of(InetAddressClass.INET6_ADDRESS, "[1.2.3.4]"),
// IPv4 address literal with BSD-formatting
Arguments.of(InetAddressClass.INET_ADDRESS, "1.2.3.0256"),
Arguments.of(InetAddressClass.INET4_ADDRESS, "1.2.3.0256"),
// Invalid IPv4-mapped IPv6 address forms
// ::FFFF:d.d.d
Arguments.of(InetAddressClass.INET_ADDRESS, "::FFFF:1.2.3"),
Arguments.of(InetAddressClass.INET6_ADDRESS, "::FFFF:1.2.3"),
// ::FFFF:d.d
Arguments.of(InetAddressClass.INET_ADDRESS, "::FFFF:1.2"),
Arguments.of(InetAddressClass.INET6_ADDRESS, "::FFFF:1.2"),
// ::d.d.d
Arguments.of(InetAddressClass.INET_ADDRESS, "::1.2.3"),
Arguments.of(InetAddressClass.INET6_ADDRESS, "::1.2.3"),
// ::d.d
Arguments.of(InetAddressClass.INET_ADDRESS, "::1.2"),
Arguments.of(InetAddressClass.INET6_ADDRESS, "::1.2"),
// IPv4-mapped IPv6 address with scope-id
Arguments.of(InetAddressClass.INET6_ADDRESS,
"::FFFF:129.144.52.38%1"),
// IPv4-mapped IPv6 addresses cannot be parsed by Inet4Address.ofLiteral
Arguments.of(InetAddressClass.INET4_ADDRESS,
"::FFFF:129.144.52.38"),
Arguments.of(InetAddressClass.INET4_ADDRESS,
"[::ffff:1.2.3.4]"),
// IPv4 literals in BSD form
Arguments.of(InetAddressClass.INET_ADDRESS, "0256.1.2.3"),
Arguments.of(InetAddressClass.INET4_ADDRESS, "1.2.0256.3"),
Arguments.of(InetAddressClass.INET_ADDRESS, "0x1.2.3.4"),
Arguments.of(InetAddressClass.INET4_ADDRESS, "1.2.0x3.4"),
Arguments.of(InetAddressClass.INET_ADDRESS, "0xFFFFFFFF"),
Arguments.of(InetAddressClass.INET4_ADDRESS, "0xFFFFFFFF"),
// invalid IPv4 literals in POSIX/BSD form
Arguments.of(InetAddressClass.INET4_ADDRESS_POSIX, "0x100.1.2.3"), // 0x100 is too large
Arguments.of(InetAddressClass.INET4_ADDRESS_POSIX, "1.2.3.0x100"),
Arguments.of(InetAddressClass.INET4_ADDRESS_POSIX, "127.08.9.1"), // 8, 9 are invalid octals
Arguments.of(InetAddressClass.INET4_ADDRESS_POSIX, "127.8.09.1"),
Arguments.of(InetAddressClass.INET4_ADDRESS_POSIX, "048"),
Arguments.of(InetAddressClass.INET4_ADDRESS_POSIX, ""), // empty
Arguments.of(InetAddressClass.INET4_ADDRESS_POSIX, "0x1FFFFFFFF"), // 2^33 - 1 is too large
Arguments.of(InetAddressClass.INET4_ADDRESS_POSIX, "0x100000000"), // 2^32 is too large
Arguments.of(InetAddressClass.INET4_ADDRESS_POSIX, "040000000000"),
// Empty literals
Arguments.of(InetAddressClass.INET_ADDRESS, ""),
Arguments.of(InetAddressClass.INET4_ADDRESS, ""),
Arguments.of(InetAddressClass.INET6_ADDRESS, ""),
// Blank literals
Arguments.of(InetAddressClass.INET_ADDRESS, " "),
Arguments.of(InetAddressClass.INET4_ADDRESS, " "),
Arguments.of(InetAddressClass.INET6_ADDRESS, " "),
Arguments.of(InetAddressClass.INET4_ADDRESS_POSIX, " ")
);
// Construct arguments for a test case with IPv6-scoped address with scope-id
// specified as a string with non-existing network interface name
String ifName = generateNonExistingIfName();
Stream<Arguments> nonExistingIFinScope = ifName.isBlank() ? Stream.empty() :
Stream.of(Arguments.of(InetAddressClass.INET6_ADDRESS,
"2001:db8:a0b:12f0::1%" + ifName));
return Stream.concat(argumentsStream, nonExistingIFinScope);
}
private static Stream<Arguments> addressToValidTestCases(InetAddress inetAddress) {
String addressLiteral = inetAddress.getHostAddress();
byte[] expectedAddressBytes = inetAddress.getAddress();
InetAddressClass addressClass = switch (inetAddress) {
case Inet4Address i4 -> InetAddressClass.INET4_ADDRESS;
case Inet6Address i6 -> InetAddressClass.INET6_ADDRESS;
case InetAddress ia -> InetAddressClass.INET_ADDRESS;
};
return Stream.of(
Arguments.of(InetAddressClass.INET_ADDRESS, addressLiteral, expectedAddressBytes),
Arguments.of(addressClass, addressLiteral, expectedAddressBytes));
}
private static String generateNonExistingIfName() {
try {
// At least two network interfaces are required to generate
// a non-existing interface name
if (NetworkInterface.networkInterfaces().count() < 2) {
return "";
}
return NetworkInterface
.networkInterfaces()
.map(NetworkInterface::getName)
.collect(Collectors.joining())
.strip();
} catch (SocketException e) {
return "";
}
}
private static Executable constructExecutable(InetAddressClass inetAddressClass, String input) {
return switch (inetAddressClass) {
case INET_ADDRESS -> () -> InetAddress.ofLiteral(input);
case INET4_ADDRESS -> () -> Inet4Address.ofLiteral(input);
case INET4_ADDRESS_POSIX -> () -> Inet4Address.ofPosixLiteral(input);
case INET6_ADDRESS -> () -> Inet6Address.ofLiteral(input);
};
}
enum InetAddressClass {
INET_ADDRESS,
INET4_ADDRESS,
INET4_ADDRESS_POSIX,
INET6_ADDRESS
}
}

View file

@ -0,0 +1,11 @@
# test hosts file for internal NameService
10.2.3.4 testHost.testDomain
10.5.6.7 testHost.testDomain
10.8.9.10
# The following lines are desirable for IPv6 capable hosts
::1 ip6-localhost ip6-loopback
fe80::1 link-local-host
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

View file

@ -0,0 +1,52 @@
/*
* Copyright (c) 2000, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 4361604
* @summary InetAddress.getByName on Solaris returns 0.0.0.0 for
* hostname that start with white space.
*/
import java.net.*;
import java.util.StringTokenizer;
public class WhiteSpaceHostTest {
public static void main(String args[]) throws Exception {
String hosts = " localhost;localhost; localhost;localhost1; localhost1; bogus.mil;\u0010localhost";
StringTokenizer tokenizer = new StringTokenizer(hosts, ";");
while (tokenizer.hasMoreTokens()) {
String hostname = tokenizer.nextToken();
InetAddress ia;
try {
ia = InetAddress.getByName(hostname);
} catch (UnknownHostException e) {
continue;
}
if (ia.isAnyLocalAddress()) {
throw new Exception("Bogus hostname lookup returned any local address");
}
}
}
}

View file

@ -0,0 +1,82 @@
/*
* Copyright (c) 2015, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8133196
* @summary test functionality of getOriginalHostName(InetAddress)
* @modules java.base/jdk.internal.access
*/
import java.net.InetAddress;
import jdk.internal.access.JavaNetInetAddressAccess;
import jdk.internal.access.SharedSecrets;
public class getOriginalHostName {
private static final JavaNetInetAddressAccess jna =
SharedSecrets.getJavaNetInetAddressAccess();
public static void main(String[] args) throws Exception {
final String HOST = "dummyserver.java.net";
InetAddress ia = null;
ia = getInetAddress(HOST);
if (ia != null) testInetAddress(ia, HOST);
ia = InetAddress.getByAddress(HOST, new byte[] { 1, 2, 3, 4});
testInetAddress(ia, HOST);
ia = InetAddress.getByName("255.255.255.0");
testInetAddress(ia, null);
ia = InetAddress.getByAddress(new byte[]{1,1,1,1});
testInetAddress(ia, null);
ia = InetAddress.getLocalHost();
testInetAddress(ia, ia.getHostName());
ia = InetAddress.getLoopbackAddress();
testInetAddress(ia, ia.getHostName());
}
private static InetAddress getInetAddress(String host) {
try {
return InetAddress.getByName(host);
} catch (java.net.UnknownHostException uhe) {
System.out.println("Skipping " + host + " due to " + uhe);
return null;
}
}
private static void testInetAddress(InetAddress ia, String expected)
throws Exception {
System.out.println("Testing InetAddress: " + ia);
System.out.println("Expecting original hostname of : " + expected);
String origHostName = jna.getOriginalHostName(ia);
System.out.println("via JavaNetAccess: " + origHostName);
if (origHostName == null && expected != null) {
throw new RuntimeException("Unexpected null. Testing:" + expected);
} else if (expected != null && !origHostName.equals(expected)) {
throw new RuntimeException("Unexpected hostname :" + origHostName);
} else if (expected == null && origHostName != null) {
throw new RuntimeException("Unexpected origHostName: " + origHostName);
}
}
}

View file

@ -0,0 +1,53 @@
/*
* Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.net;
import java.net.spi.InetAddressResolver.LookupPolicy;
public class NullCharInHostname {
public static void main(String[] args) {
var name = "foo\u0000bar";
System.out.println("file.encoding = " + System.getProperty("file.encoding"));
System.out.println("native.encoding = " + System.getProperty("native.encoding"));
// This should throw IAE as it calls the internal impl
try {
var impl = new Inet6AddressImpl();
var addrs = impl.lookupAllHostAddr(name, LookupPolicy.of(LookupPolicy.IPV4));
} catch (UnknownHostException e0) {
throw new RuntimeException(e0);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
// This should throw UHE as before and not IAE for compatibility
try {
var addrs = InetAddress.getByName(name);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (UnknownHostException e0) {
e0.printStackTrace();
}
}
}

View file

@ -0,0 +1,10 @@
grant {
permission javax.security.auth.AuthPermission "modifyPrincipals";
permission javax.security.auth.AuthPermission "doAsPrivileged";
permission java.util.PropertyPermission "*", "read,write";
};
grant Principal MyPrincipal "test" {
permission java.net.SocketPermission "${host.name}", "resolve";
};

View file

@ -0,0 +1,149 @@
/*
* Copyright (c) 2002, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* Lookup/reverse lookup class for regression test 4773521
* @test
* @bug 4773521
* @summary Test that reverse lookups of IPv4 addresses work when IPv6
* is enabled
* @library /test/lib
* @build jdk.test.lib.Utils
* jdk.test.lib.Asserts
* jdk.test.lib.JDKToolFinder
* jdk.test.lib.JDKToolLauncher
* jdk.test.lib.Platform
* jdk.test.lib.process.*
* Lookup
* @run main Lookup root
*
*/
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.stream.Stream;
import java.util.stream.Collectors;
import jdk.test.lib.process.OutputAnalyzer;
import jdk.test.lib.process.ProcessTools;
import jtreg.SkippedException;
public class Lookup {
private static final String HOST = "icann.org";
private static final String SKIP = "SKIP";
public static void main(String args[]) throws IOException {
String addr = null;
String ipv4Name = null;
String ipv4Reversed = null;
if (args.length == 0) {
// called from lookupWithIPv4Prefer
// obtain an IPv4 address from the hostname.
try {
InetAddress ia = InetAddress.getByName(HOST);
addr = ia.getHostAddress();
ia = InetAddress.getByName(addr);
System.out.print(addr + ":" + ia.getHostName());
return;
} catch (UnknownHostException e) {
System.out.print(SKIP);
return;
}
} else if (args.length == 2 && args[0].equals("reverse")) {
// called from reverseWithIPv4Prefer
// Check that IPv4 address can be resolved to host
// with -Djava.net.preferIPv4Stack=true
try {
InetAddress ia = InetAddress.getByName(args[1]);
addr = ia.getHostAddress();
ipv4Reversed = ia.getHostName();
System.out.print(addr + ":" + ipv4Reversed);
return;
} catch (UnknownHostException e) {
System.out.print(SKIP);
return;
}
} else if (args.length != 1 || !args[0].equals("root")) {
throw new IllegalArgumentException(Stream.of(args).collect(Collectors.joining(" ")));
}
// spawn a subprocess to obtain the IPv4 address
String tmp = lookupWithIPv4Prefer();
System.out.println("IPv4 lookup results: [" + tmp + "]");
if (SKIP.equals(tmp)) {
throw new SkippedException(HOST + " can't be resolved - test skipped.");
}
String[] strs = tmp.split(":");
addr = strs[0];
ipv4Name = strs[1];
// check that the reverse lookup of the IPv4 address
// will succeed with the IPv4 only stack
tmp = reverseWithIPv4Prefer(addr);
System.out.println("IPv4 reverse lookup results: [" + tmp + "]");
if (SKIP.equals(tmp)) {
throw new SkippedException(addr + " can't be resolved with preferIPv4 - test skipped.");
}
strs = tmp.split(":");
ipv4Reversed = strs[1];
// Now check that a reverse lookup will succeed with the dual stack.
InetAddress ia = InetAddress.getByName(addr);
String name = ia.getHostName();
// output details of dual stack lookup by address
System.out.println("dual stack lookup for addr " + addr + " returned IP address " + ia);
System.out.println(" with hostname " + name);
System.out.println("(default) " + addr + "--> " + name
+ " (reversed IPv4: " + ipv4Reversed + ")");
if (!ipv4Name.equals(name)) {
// adding some diagnosting
System.err.println("name=" + name + " doesn't match expected=" + ipv4Name);
System.err.println("Listing all adresses:");
for (InetAddress any : InetAddress.getAllByName(HOST)) {
System.err.println("\t[" + any + "] address=" + any.getHostAddress()
+ ", host=" + any.getHostName());
}
// make the test fail...
throw new RuntimeException("Mismatch between default"
+ " and java.net.preferIPv4Stack=true results");
}
}
static String lookupWithIPv4Prefer() throws IOException {
String testClz = Lookup.class.getName();
ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(
"-Djava.net.preferIPv4Stack=true", testClz);
return new OutputAnalyzer(pb.start()).getOutput();
}
static String reverseWithIPv4Prefer(String addr) throws IOException {
String testClz = Lookup.class.getName();
ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(
"-Djava.net.preferIPv4Stack=true", testClz, "reverse", addr);
return new OutputAnalyzer(pb.start()).getOutput();
}
}