Java IP Address to Long ipToLong(byte[] address)

Here you can find the source of ipToLong(byte[] address)

Description

A convenient method that accepts an IP address represented by a byte[] of size 4 and returns this as a long representation of the same IP address.

License

Open Source License

Parameter

Parameter Description
address the byte[] of size 4 representing the IP address.

Return

a long representation of the IP address.

Declaration

public static long ipToLong(byte[] address) 

Method Source Code

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

public class Main {
    /**/*ww  w  . j  a  v a  2 s.c o  m*/
     * A convenient method that accepts an IP address represented by a byte[]
     * of size 4 and returns this as a long representation of the same IP
     * address.
     *
     * @param address the byte[] of size 4 representing the IP address.
     * 
     * @return a long representation of the IP address.
     */
    public static long ipToLong(byte[] address) {
        if (address.length != 4) {
            throw new IllegalArgumentException("byte array must be of length 4");
        }
        long ipNum = 0;
        long multiplier = 1;
        for (int i = 3; i >= 0; i--) {
            int byteVal = (address[i] + 256) % 256;
            ipNum += byteVal * multiplier;
            multiplier *= 256;
        }
        return ipNum;
    }
}

Related

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