Here you can find the source of getIPv4LocalNetMask(InetAddress ip, int netPrefix)
private static InetAddress getIPv4LocalNetMask(InetAddress ip, int netPrefix)
//package com.java2s; //License from project: Open Source License import java.net.InetAddress; public class Main { /**//from w w w . jav a 2 s . co m * Gets network mask for the IP address and network prefix specified. * The network mask will be returned has an IP, use .getHostAddress() for string representation.. */ private static InetAddress getIPv4LocalNetMask(InetAddress ip, int netPrefix) { try { // since this is for IPv4, it's 32 bits, so set the sign value of the int to "negative". int shiftby = (1 << 31); // for the number of bits of the prefix -1 (we already set the sign bit) for (int i = netPrefix - 1; i > 0; i--) { // shift the sign right; Java makes the sign bit sticky on a shift. // so no need to "set it back up"... shiftby = (shiftby >> 1); } // transform the resulting value in xxx.xxx.xxx.xxx format, like if it was a standard address. String maskString = Integer.toString((shiftby >> 24) & 255) + "." + Integer.toString((shiftby >> 16) & 255) + "." + Integer.toString((shiftby >> 8) & 255) + "." + Integer.toString(shiftby & 255); // return the address return InetAddress.getByName(maskString); } catch (Exception e) { e.printStackTrace(); } return null; } }