Java examples for Network:IP Address
IP subnet Address
//package com.java2s; import java.net.InetAddress; import java.net.UnknownHostException; public class Main { public static InetAddress subnetAddress(InetAddress address, int networkPrefixLength) throws IllegalArgumentException { byte[] rawAddress = address.getAddress(); byte[] newRawAddress = new byte[rawAddress.length]; int count = 0; for (int i = 0; i < rawAddress.length; i++) { byte octet = 0x00; if (count < networkPrefixLength) { int value; for (int bit = 7; bit >= 0; bit--) { value = 0x00;/* www . ja v a 2 s . c o m*/ if (count < networkPrefixLength) { value = ((rawAddress[i] >>> bit) & 0x01); } octet |= ((value & 0x01) << bit); count++; } } newRawAddress[i] = octet; } try { return InetAddress.getByAddress(newRawAddress); } catch (UnknownHostException e) { throw new IllegalArgumentException( "Internet Address must contain either 4 or 16 octets!"); } } }