Here you can find the source of getNetworkCIDR(InetAddress addr, short prefixLength)
private static String getNetworkCIDR(InetAddress addr, short prefixLength)
//package com.java2s; /*/* w ww .ja v a 2s.c o m*/ * Copyright (c) 2008-2011 by Jan Stender, * Zuse Institute Berlin * * Licensed under the BSD License, see LICENSE file for details. * */ import java.net.Inet6Address; import java.net.InetAddress; import java.net.UnknownHostException; public class Main { private static String getNetworkCIDR(InetAddress addr, short prefixLength) { byte[] raw = addr.getAddress(); // If the address is more then 32bit long it has to be an v6 address. boolean isV6 = raw.length > 4; // Get the number of fields that are network specific and null the remaining host fields. int networkFields = prefixLength / 8; for (int i = networkFields + 1; i < raw.length; i++) { raw[i] = 0x00; } // Get the remaining bytes attributed to the network amidst a byte field. int networkRemainder = prefixLength % 8; if (networkFields < raw.length) { // Construct a 8bit mask, with bytes set for the network. byte mask = (byte) (0xFF << (8 - networkRemainder)); raw[networkFields] = (byte) (raw[networkFields] & mask); } StringBuilder sb = new StringBuilder(); // Use the InetAddress implementation to convert the raw byte[] to a string. try { sb.append(InetAddress.getByAddress(raw).getHostAddress()); } catch (UnknownHostException e) { // This should never happen, since the foundation of every calculation is the byte array // returned by a valid InetAddress. throw new RuntimeException(e); } sb.append("/").append(prefixLength); return sb.toString(); } public static String getHostAddress(InetAddress host) { String hostAddr = host.getHostAddress(); if (host instanceof Inet6Address) { if (hostAddr.lastIndexOf('%') >= 0) { hostAddr = hostAddr.substring(0, hostAddr.lastIndexOf('%')); } } return hostAddr; } }