Java IP Address to Long ipToLong(String addr)

Here you can find the source of ipToLong(String addr)

Description

ip To Long

License

Open Source License

Declaration

public static long ipToLong(String addr) 

Method Source Code

//package com.java2s;

public class Main {
    private static final int SLASHNET_VALUE = 32;
    private static final int TWO_FIVE_SIX = 256;
    private static final int TWO_FIVE_FIVE = 255;
    private static final int THREE = 3;
    private static final String SLASH = "/";
    private static final int NUMBER_OF_BITS_IN_IP = 32;

    public static long ipToLong(String addr) {
        String ipAddress = addr;//from   w  w  w.j a  va 2 s .co m
        long netMask = 0;
        if (addr.contains(SLASH)) {
            String[] addressAndSubnet = addr.split(SLASH);
            netMask = addrsInSlashnet(Integer.valueOf(addressAndSubnet[1]));
            ipAddress = addressAndSubnet[0];
        }
        String[] addrArray = ipAddress.split("\\.");
        long num = 0;
        for (int i = 0; i < addrArray.length; i++) {
            try {
                if (Integer.parseInt(addrArray[i]) > TWO_FIVE_FIVE)
                    throw new IllegalArgumentException("IP address out of range");
                int power = THREE - i;
                num += Integer.parseInt(addrArray[i]) % TWO_FIVE_SIX * Math.pow(TWO_FIVE_SIX, power);
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException(String.format("Failed to parse IP address %s", addr));
            }
        }
        // throw the ip on the back of the netmask.
        num = netMask << NUMBER_OF_BITS_IN_IP | num;
        return num;
    }

    public static int addrsInSlashnet(int slashnet) {
        int delta = SLASHNET_VALUE - slashnet;
        return (int) Math.pow(2, delta);
    }
}

Related

  1. ip2Long(String ipaddress)
  2. ip2Long(String ipAddress)
  3. ipToLong(byte[] address)
  4. ipToLong(byte[] octets)
  5. ipToLong(final String addr)
  6. ipTolong(String address)
  7. ipToLong(String ip)
  8. ipToLong(String ip)
  9. ipToLong(String ip)