Java IP Address to Long ipV4AddressToLong(String ipAddress)

Here you can find the source of ipV4AddressToLong(String ipAddress)

Description

Converts an IP address string like 192.168.0.1 to an internal long value

License

Open Source License

Parameter

Parameter Description
ipAddress a parameter

Exception

Parameter Description
UnknownHostException if the address is not a valid IPv4 address

Return

long the numerical representation of the address

Declaration

public static long ipV4AddressToLong(String ipAddress) 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 {
    /**/* www.j av  a2  s.  co  m*/
     * 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 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;
    }
}

Related

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