Java IP Address to Long ipv4CidrToLong(String networkCidr)

Here you can find the source of ipv4CidrToLong(String networkCidr)

Description

Converts / format ie.

License

Open Source License

Parameter

Parameter Description
networkCidr a parameter

Exception

Parameter Description

Return

long[] - an array of long the address being element 0 and the CIDR being element 1

Declaration

public static long[] ipv4CidrToLong(String networkCidr) throws UnknownHostException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.net.InetAddress;
import java.net.UnknownHostException;

public class Main {
    /**//from w  w w .  ja  v a  2s. c o  m
     * Converts <IP>/<CIDR> format ie. 10.0.3.55/25, to an array of long with two elements
     *
     * @param networkCidr
     * @return long[] - an array of long the address being element 0 and the CIDR being element 1
     * @throws java.net.UnknownHostException
     */
    public static long[] ipv4CidrToLong(String networkCidr) throws UnknownHostException {
        String[] strNets = networkCidr.split("/");
        return new long[] { ipV4AddressToLong(strNets[0]), convertStrCidrToLong(strNets[1]) };
    }

    /**
     * Converts an IP address string like 192.168.0.1 to an internal long value
     *
     * @param ipAddress
     * @return long the numerical representation of the address
     * @throws UnknownHostException if the address is not a valid IPv4 address
     */
    public static long ipV4AddressToLong(String ipAddress) throws UnknownHostException {

        byte[] bytes = InetAddress.getByName(ipAddress).getAddress();

        return convertByteToLong(bytes);
    }

    private static long convertStrCidrToLong(String strCidr) {
        int intCidr = new Integer(strCidr);
        return convertCidrToLong(intCidr);
    }

    private static long convertByteToLong(byte[] ipBytes) {

        long unsignedInt = 0;

        for (int i = 0; i < ipBytes.length; i++) {
            unsignedInt |= ((0x000000FF & ((int) ipBytes[i])) << ((ipBytes.length - i - 1) * 8));
        }

        return unsignedInt & 0xFFFFFFFFL;
    }

    public static long convertCidrToLong(int cidr) {

        if (cidr > 32 || cidr < 0)
            throw new IllegalArgumentException(
                    "[" + cidr + "]" + " is invalid, CIDR must be greater that 0 and less than 32");

        return ((0xFFFFFFFFL << (32 - cidr)) & 0xFFFFFFFFL);
    }
}

Related

  1. ipToLong(String ipStr)
  2. ipToLong(String sip)
  3. ipToLong(String strIP)
  4. ipv4(long ip)
  5. ipV4AddressToLong(String ipAddress)
  6. ipV4ToLong(final String ipAddress)
  7. ipv4ToLong(final String ipv4)
  8. ipV4ToLong(String ip)