Java IP Address to Long ipv4ToLong(final String ipv4)

Here you can find the source of ipv4ToLong(final String ipv4)

Description

IPv4 to Long.

License

Apache License

Parameter

Parameter Description
ipv4 a parameter

Return

-lL if not a ip.

Declaration

public static long ipv4ToLong(final String ipv4) 

Method Source Code

//package com.java2s;
/**// ww  w. j  a  v a2  s.c o m
 * Copyright 2013-present febit.org (support@febit.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

public class Main {
    /**
     * IPv4 to Long.
     *
     * TODO: refactor
     *
     * @param ipv4
     * @return -lL if not a ip.
     */
    public static long ipv4ToLong(final String ipv4) {
        if (ipv4 == null) {
            return -1L;
        }
        final int length = ipv4.length();
        if (length < 7 || length > 15) {
            return -1L;
        }

        char[] chars = new char[length + 1];
        chars[length] = '.';
        ipv4.getChars(0, length, chars, 0);

        int i = 0;

        int pieceCount = 0;
        long result = 0;
        int piece = 0;
        while (i <= length) {
            char c = chars[i++];
            switch (c) {
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
                piece = piece * 10 + c - '0';
                continue;
            case '.':
                pieceCount++;
                if (pieceCount > 4) {
                    return -1L;
                }
                if ((piece | 0xFF) != 0xFF) {
                    return -1L;
                }
                result = (result << 8) + piece;
                piece = 0;
                continue;
            default:
                return -1L;
            }
        }
        return result;
    }
}

Related

  1. ipToLong(String strIP)
  2. ipv4(long ip)
  3. ipV4AddressToLong(String ipAddress)
  4. ipv4CidrToLong(String networkCidr)
  5. ipV4ToLong(final String ipAddress)
  6. ipV4ToLong(String ip)