Path: blob/master/test/jdk/java/net/InterfaceAddress/NetworkPrefixLength.java
41149 views
/*1* Copyright (c) 2010, 2013, 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/* @test24* @bug 6707289 710788325* @summary InterfaceAddress.getNetworkPrefixLength() does not conform to Javadoc26*/2728import java.net.InetAddress;29import java.net.Inet4Address;30import java.net.InterfaceAddress;31import java.net.NetworkInterface;32import java.util.Enumeration;33import static java.lang.System.out;3435public class NetworkPrefixLength {36static boolean passed = true;3738public static void main(String[] args) throws Exception {39Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();4041while (nics.hasMoreElements()) {42NetworkInterface nic = nics.nextElement();43for (InterfaceAddress iaddr : nic.getInterfaceAddresses()) {44boolean valid = checkPrefix(iaddr);45if (!valid) {46passed = false;47debug(nic.getName(), iaddr);48}49InetAddress ia = iaddr.getAddress();50if (ia.isLoopbackAddress() && ia instanceof Inet4Address) {51// assumption: prefix length will always be 852if (iaddr.getNetworkPrefixLength() != 8) {53out.println("Expected prefix of 8, got " + iaddr);54passed = false;55}56}57}58}5960if (!passed)61throw new RuntimeException("Failed: some interfaces have invalid prefix lengths");62}6364static boolean checkPrefix(InterfaceAddress iaddr) {65InetAddress addr = iaddr.getAddress();6667if (addr instanceof Inet4Address)68return checkIPv4PrefixLength(iaddr.getNetworkPrefixLength());69else70return checkIPv6PrefixLength(iaddr.getNetworkPrefixLength());71}7273static boolean checkIPv4PrefixLength(int prefix) {74if (prefix >=0 && prefix <= 32)75return true;7677return false;78}7980static boolean checkIPv6PrefixLength(int prefix) {81if (prefix >=0 && prefix <= 128)82return true;8384return false;85}8687static void debug(String nicName, InterfaceAddress iaddr) {88out.println("NIC " + nicName + " has an address with an invalid prefix length:\n" + iaddr);89}90}91929394