Java examples for Network:Network Address
get Sub Network Address Range
//package com.java2s; public class Main { /**//w w w . jav a 2 s .com * * @param hostAddress * ,ex: 192.168.1.222 * @param networkPrefixLength * ,ex: 24 * @return */ public static byte[][] getSubNetworkAddressRange(String hostAddress, short networkPrefixLength) { byte[] addressBytes = getBytesOfHostAddress(hostAddress); byte[][] addressRange = new byte[2][]; addressRange[0] = new byte[addressBytes.length]; addressRange[1] = new byte[addressBytes.length]; final int addressBitLength = addressBytes.length * 8; for (int i = 0; i < addressBytes.length; i++) { if ((i + 1) * 8 + networkPrefixLength <= addressBitLength) { // host addressRange[0][i] = 0; addressRange[1][i] = (byte) 0xff; } else if (i * 8 + networkPrefixLength < addressBitLength) { // host and network addressRange[0][i] = addressRange[1][i] = addressBytes[i]; byte bits = (byte) 0xff; int moveBitCount = 8 - networkPrefixLength % 8; bits = (byte) (bits >>> moveBitCount << moveBitCount); addressRange[0][i] &= bits; addressRange[1][i] |= (~bits); } else { // network addressRange[0][i] = addressRange[1][i] = addressBytes[i]; } } if (addressRange[0][0] == 0) { addressRange[0][0] = 1; } if (addressRange[1][0] == (byte) 0xff) { addressRange[1][0]--; } return addressRange; } /** * * @param hostAddress * ex:192.168.1.222 * @return */ public static byte[] getBytesOfHostAddress(String hostAddress) { String[] hostAddressParts = hostAddress.split("\\."); byte[] bytes = new byte[hostAddressParts.length]; for (int i = 0; i < hostAddressParts.length; i++) { bytes[i] = (byte) Short.parseShort(hostAddressParts[i]); } final int halfBytesLength = bytes.length / 2; for (int i = 0; i < halfBytesLength; i++) { final byte b = bytes[i]; bytes[i] = bytes[bytes.length - 1 - i]; bytes[bytes.length - 1 - i] = b; } return bytes; } }