Here you can find the source of getSubnetPrefix(InetAddress ip, int maskLen)
Parameter | Description |
---|---|
ip | the IP address in InetAddress form |
maskLen | the length of the prefix network mask |
public static InetAddress getSubnetPrefix(InetAddress ip, int maskLen)
//package com.java2s; /*//from w w w .j a va2 s .c om * Copyright (c) 2013-2014 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ import java.net.InetAddress; import java.net.UnknownHostException; public class Main { /** * Given an IP address and a prefix network mask length, it returns the * equivalent subnet prefix IP address Example: for ip = "172.28.30.254" and * maskLen = 25 it will return "172.28.30.128" * * @param ip the IP address in InetAddress form * @param maskLen the length of the prefix network mask * @return the subnet prefix IP address in InetAddress form */ public static InetAddress getSubnetPrefix(InetAddress ip, int maskLen) { int bytes = maskLen / 8; int bits = maskLen % 8; byte modifiedByte; byte[] sn = ip.getAddress(); if (bits > 0) { modifiedByte = (byte) (sn[bytes] >> (8 - bits)); sn[bytes] = (byte) (modifiedByte << (8 - bits)); bytes++; } for (; bytes < sn.length; bytes++) { sn[bytes] = (byte) (0); } try { return InetAddress.getByAddress(sn); } catch (UnknownHostException e) { return null; } } }