Étant donné une adresse CIDR, par exemple 192.168.10.0/24
24
)255.255.255.0
)192.168.10.0
)Il est couvert par les utils Apache.
Voir cette URL: http://commons.Apache.org/proper/commons-net/apidocs/org/Apache/commons/net/util/SubnetUtils.html
String subnet = "192.168.0.3/31";
SubnetUtils utils = new SubnetUtils(subnet);
utils.getInfo().isInRange(address)
Remarque: Pour utiliser les sous-réseaux CIDR avec// 32, par exemple, il faut ajouter la déclaration suivante:
utils.setInclusiveHostCount(true);
Voici comment vous le feriez en Java,
String[] parts = addr.split("/");
String ip = parts[0];
int prefix;
if (parts.length < 2) {
prefix = 0;
} else {
prefix = Integer.parseInt(parts[1]);
}
int mask = 0xffffffff << (32 - prefix);
System.out.println("Prefix=" + prefix);
System.out.println("Address=" + ip);
int value = mask;
byte[] bytes = new byte[]{
(byte)(value >>> 24), (byte)(value >> 16 & 0xff), (byte)(value >> 8 & 0xff), (byte)(value & 0xff) };
InetAddress netAddr = InetAddress.getByAddress(bytes);
System.out.println("Mask=" + netAddr.getHostAddress());
Suite à la réponse de Yuriy: Pour obtenir l’ensemble des adresses IP, la classe Apache Java SubnetUtils propose les méthodes suivantes:
String[] addresses = utils.getInfo().getAllAddresses();
Pour télécharger le fichier jar contenant la classe, allez à: http://repo1.maven.org/maven2/commons-net/commons-net/3.0.1/commons-net-3.0.1.jar
Le code source: http://svn.Apache.org/viewvc/commons/proper/net/trunk/src/main/Java/org/Apache/commons/net/util/SubnetUtils.java?view = balisage
Identifiant Maven:
<groupId> <artifactId>
commons-net<artifactId> <version>
3.0.1 <version>
La bibliothèque Java IPAddress prend en charge IPv4 et IPv6 de manière polymorphe, y compris les sous-réseaux. Le javadoc est disponible sur le lien. Disclaimer: Je suis le chef de projet.
Tous les cas d'utilisation que vous avez énumérés sont pris en charge pour IPv4 et Ipv6 de manière transparente.
String str = "192.168.10.0/24";
IPAddressString addrString = new IPAddressString(str);
try {
IPAddress addr = addrString.toAddress();
Integer prefix = addr.getNetworkPrefixLength(); //24
IPAddress mask = addr.getNetwork().getNetworkMask(prefix, false);//255.255.255.0
IPAddress networkAddr = addr.mask(mask); //192.168.10.0
IPAddress networkAddrOtherWay = addr.getLower().removePrefixLength(); //192.168.10.0
...
} catch(AddressStringException e) {
//e.getMessage provides validation issue
}
Ligne de commande Linux ipcalc . Vous pouvez rapidement utiliser:
$ipcalc 192.168.10.0/24
Address: 192.168.10.0 11000000.10101000.00001010. 00000000
Netmask: 255.255.255.0 = 24 11111111.11111111.11111111. 00000000
Wildcard: 0.0.0.255 00000000.00000000.00000000. 11111111
=>
Network: 192.168.10.0/24 11000000.10101000.00001010. 00000000
HostMin: 192.168.10.1 11000000.10101000.00001010. 00000001
HostMax: 192.168.10.254 11000000.10101000.00001010. 11111110
Broadcast: 192.168.10.255 11000000.10101000.00001010. 11111111
Hosts/Net: 254 Class C, Private Internet
L'algorithme est en pseudo-code (en réalité PHP), vous pouvez le traduire vous-même en Java.
Algoritm de ici .
//$ipNetmask = "192.168.1.12/30";
list($ip, $netmask) = split( "/", $ipNetmask );
$ip_elements_decimal = split( "[.]", $ip );
$netmask_result="";
for($i=1; $i <= $netmask; $i++) {
$netmask_result .= "1";
}
for($i=$netmask+1; $i <= 32; $i++) {
$netmask_result .= "0";
}
$netmask_ip_binary_array = str_split( $netmask_result, 8 );
$netmask_ip_decimal_array = array();
foreach( $netmask_ip_binary_array as $k => $v ){
$netmask_ip_decimal_array[$k] = bindec( $v ); // "100" => 4
$network_address_array[$k] = ( $netmask_ip_decimal_array[$k] & $ip_elements_decimal[$k] );
}
$network_address = join( ".", $network_address_array );
// ------------------------------------------------
// TCP/IP NETWORK INFORMATION
// ------------------------------------------------
// IP Entered = ..................: 192.168.1.12
// CIDR = ........................: /30
// Netmask = .....................: 255.255.255.252
// Network Address = .............: 192.168.1.12
// Broadcast Address = ...........: 192.168.1.15
// Usable IP Addresses = .........: 2
// First Usable IP Address = .....: 192.168.1.13
// Last Usable IP Address = ......: 192.168.1.14
Vous pouvez utiliser org.springframework.security.web.util.IpAddressMatcher
à partir de Spring Framework.
c'est mon groovy :)
//IP calculator by ku1gun
// input
String inputAddr = "12.34.56.78/20";
//magic
def(String ipAddrBin, String maskAddrBin, String invertedMaskBin, int hostsCount) = getIpAddrAndCidrMaskBin(inputAddr);
String broadcastAddr = retrieveBroadcastAddr(ipAddrBin, invertedMaskBin);
String ipAddr = getTenBaseAddrValueFromBin(ipAddrBin);
String maskAddr = getTenBaseAddrValueFromBin(maskAddrBin);
String invertedMask = getTenBaseAddrValueFromBin(invertedMaskBin);
String networkAddr = retrieveNetworkAddr(ipAddrBin, maskAddrBin);
def (String ipMinVal, String ipMaxVal) = getMinMaxIpRangeValues(networkAddr, broadcastAddr)
//Output "debug" results
System.out.println("Variables:");
System.out.println("ipInput: " + ipAddr);
System.out.println("MaskInput: " + maskAddr);
System.out.println("invertedMask: " + invertedMask);
System.out.println("-----------------------");
System.out.println("Binaries:");
System.out.println("ipBin: " + ipAddrBin);
System.out.println("MaskInBin: " + maskAddrBin);
System.out.println("InvertedMaskBin: " + invertedMaskBin);
System.out.println("-----------------------");
System.out.println("Results:");
System.out.println("maskAddr: " + maskAddr);
System.out.println("hostsCount: " + hostsCount);
System.out.println("networkAddr: " + networkAddr);
System.out.println("broadcastAddr: " + broadcastAddr);
System.out.println("ipMinVal: " + ipMinVal);
System.out.println("ipMaxVal: " + ipMaxVal);
System.out.println("-----------------------");
System.out.println("IP range list:");
long ipStart = Host2long(ipMinVal);
long ipEnd = Host2long(ipMaxVal);
for (long i=ipStart; i<=ipEnd; i++)
{
System.out.println(long2dotted(i));
}
//general methods
def getIpAddrAndCidrMaskBin(String inputAddrStr)
{
def netMask = "";
def invNetMask = "";
def cidrAddressList = inputAddrStr.tokenize("\\/")
def baseIPAddress = cidrAddressList.first()
def cidrIPMask = cidrAddressList.last().toInteger()
//retrieve binaryNetMask and binaryInvertedNetMask
for(i=0; i<32; i++)
{
if(i<cidrIPMask)
{
netMask = netMask + "1";
invNetMask = invNetMask + "0";
}
else
{
netMask = netMask + "0";
invNetMask = invNetMask + "1";
}
}
//retrieve binaryIpAddress
String[] addrOctetArray = baseIPAddress.split("\\.");
String binAddr = "";
for (String string : addrOctetArray)
{
int octet = Integer.parseInt(string);
String binaryOctet = String.format("%8s", Integer.toBinaryString(octet)).replace(' ', '0');
binAddr = binAddr + binaryOctet;
}
hostsCount = 2**(32 - cidrIPMask) - 2;
return [binAddr, netMask, invNetMask, hostsCount]
}
def getTenBaseAddrValueFromBin(String binVal)
{
tenBaseAddr = "";
tenBaseAddr = tenBaseAddr + Integer.parseInt(binVal.substring(0,8), 2) + "." + Integer.parseInt(binVal.substring(8,16), 2) + "." + Integer.parseInt(binVal.substring(16,24), 2) + "." + Integer.parseInt(binVal.substring(24,32), 2)
return tenBaseAddr;
}
def retrieveBroadcastAddr(String ipAddrBin, String invertedMaskBin)
{
def oct_1 = Integer.parseInt(ipAddrBin.substring(0,8), 2) | Integer.parseInt(invertedMaskBin.substring(0,8), 2);
def oct_2 = Integer.parseInt(ipAddrBin.substring(8,16), 2) | Integer.parseInt(invertedMaskBin.substring(8,16), 2);
def oct_3 = Integer.parseInt(ipAddrBin.substring(16,24), 2) | Integer.parseInt(invertedMaskBin.substring(16,24), 2);
def oct_4 = Integer.parseInt(ipAddrBin.substring(24,32), 2) | Integer.parseInt(invertedMaskBin.substring(24,32), 2);
def t_oct = oct_1 + "."+ oct_2 + "." + oct_3 + "." + oct_4;
return t_oct
}
def retrieveNetworkAddr(String ipAddrBin, String maskInBin)
{
def oct_1 = Integer.parseInt(ipAddrBin.substring(0,8), 2) & Integer.parseInt(maskInBin.substring(0,8), 2);
def oct_2 = Integer.parseInt(ipAddrBin.substring(8,16), 2) & Integer.parseInt(maskInBin.substring(8,16), 2);
def oct_3 = Integer.parseInt(ipAddrBin.substring(16,24), 2) & Integer.parseInt(maskInBin.substring(16,24), 2);
def oct_4 = Integer.parseInt(ipAddrBin.substring(24,32), 2) & Integer.parseInt(maskInBin.substring(24,32), 2);
def t_oct = oct_1 + "."+ oct_2 + "." + oct_3 + "." + oct_4;
return t_oct
}
def getMinMaxIpRangeValues(networkAddr, broadcastAddr)
{
String[] ipAddrOctetArray = networkAddr.split("\\.");
String[] broadcastOctetArray = broadcastAddr.split("\\.");
String minRangeVal = ipAddrOctetArray[0] + "." + ipAddrOctetArray[1] + "." + ipAddrOctetArray[2] + "." + (Integer.parseInt(ipAddrOctetArray[3]) + 1)
String maxRangeVal = broadcastOctetArray[0] + "." +broadcastOctetArray[1] + "." +broadcastOctetArray[2] + "." + (Integer.parseInt(broadcastOctetArray[3]) - 1)
return[minRangeVal, maxRangeVal]
}
//IP list generate
public static long Host2long(String Host)
{
long ip=0;
if (!Character.isDigit(Host.charAt(0))) return -1;
int[] addr = ip2intarray(Host);
if (addr == null) return -1;
for (int i=0;i<addr.length;++i)
{
ip += ((long)(addr[i]>=0 ? addr[i] : 0)) << 8*(3-i);
}
return ip;
}
public static int[] ip2intarray(String Host)
{
Integer[] address = [-1,-1,-1,-1];
int i=0;
StringTokenizer tokens = new StringTokenizer(Host,".");
if (tokens.countTokens() > 4) return null;
while (tokens.hasMoreTokens())
{
try
{
address[i++] = Integer.parseInt(tokens.nextToken()) & 0xFF;
}
catch(NumberFormatException nfe)
{
return null;
}
}
return address;
}
public static String long2dotted(long ip)
{
// if ip is bigger than 255.255.255.255 or smaller than 0.0.0.0
if (ip > 4294967295l || ip < 0)
{
throw new IllegalArgumentException("invalid ip");
}
StringBuilder ipAddress = new StringBuilder();
for (int i = 3; i >= 0; i--) {
int shift = i * 8;
ipAddress.append((ip & (0xff << shift)) >> shift);
if (i > 0) {
ipAddress.append(".");
}
}
return ipAddress.toString();
}
La classe Apache Java SubnetUtils offre une aide pour effectuer certaines de ces tâches:
String[] parts = ipv4Cidr.split("/");
if (parts[1].equals("0"))
{
// This accepts all ip addresses. Technically not a subnet.
maskLength = 0;
maskAdress = "0.0.0.0"
}
else
{
maskLength = Integer.parseInt(parts[1]);
cidrInfo = new SubnetUtils(ipv4Cidr).getInfo();
maskAdress = cidrInfo.asInteger(cidrInfo.getNetmask());
networkAddress = cidrInfo.getNetworkAddress()
}
Voici un exemple simple Groovy
def cidrAddress = '192.168.10.0/24'
def cidrAddressList = cidrAddress.tokenize("\\/")
def baseIPAddress = cidrAddressList.first()
def cidrIPMask = cidrAddressList.last().toInteger()
def netMaskList = []
Integer fullOctets = cidrIPMask.intdiv(8)
fullOctets.times {netMaskList.add('255')}
def remainder = cidrIPMask % 8
netMaskList.add((256 - (2 ** (8 - remainder))).toString())
netMaskList.addAll(['0','0','0','0'])
def netMask = netMaskList.flatten().getAt(0..3).join('.')
return [cidrAddress,baseIPAddress,cidrIPMask,netMask]