1 /* 2 * Copyright (c) 2002, 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 package test.java.net.InetAddress; 24 25 /* 26 * @test 27 * @bug 4687909 28 * @summary Check Inet6Address.hashCode returns a reasonable spread of hash 29 * codes. 30 * @key randomness 31 */ 32 import java.net.InetAddress; 33 import java.net.UnknownHostException; 34 import java.util.Random; 35 import org.testng.annotations.Test; 36 import static org.testng.Assert.fail; 37 38 public class HashSpread { 39 40 static Random r = new Random(); 41 42 /** 43 * Generate and return a random IPv6 address. 44 */ randomIPv6Adress()45 static InetAddress randomIPv6Adress() { 46 StringBuffer sb = new StringBuffer(); 47 48 for (int i=0; i<8; i++) { 49 50 if (i > 0) 51 sb.append(":"); 52 53 for (int j=0; j<4; j++) { 54 int v = r.nextInt(16); 55 if (v < 10) { 56 sb.append(Integer.toString(v)); 57 } else { 58 char c = (char) ('A' + v - 10); 59 sb.append(c); 60 } 61 } 62 } 63 64 try { 65 return InetAddress.getByName(sb.toString()); 66 } catch (UnknownHostException x) { 67 throw new Error("Internal error in test"); 68 } 69 } 70 71 @Test testHashSpread()72 public void testHashSpread() throws Exception { 73 74 int iterations = 10000; 75 76 int MIN_SHORT = (int)Short.MIN_VALUE; 77 int MAX_SHORT = (int)Short.MAX_VALUE; 78 79 /* 80 * Iterate through 10k hash codes and count the number 81 * in the MIN_SHORT-MAX_SHORT range. 82 */ 83 int narrow = 0; 84 for (int i=0; i<iterations; i++) { 85 int hc = randomIPv6Adress().hashCode(); 86 if (hc >= MIN_SHORT && hc <= MAX_SHORT) { 87 narrow++; 88 } 89 } 90 91 /* 92 * If >85% of hash codes in the range then fail. 93 */ 94 double percent = (double)narrow / (double)iterations * 100.0; 95 if (percent > 85.0) { 96 fail(percent + " of hash codes were in " + 97 MIN_SHORT + " to " + MAX_SHORT + " range."); 98 } 99 100 } 101 102 }