Java IP Address Get getLongIp(String ipString)

Here you can find the source of getLongIp(String ipString)

Description

Convert Ip from String to Long.

License

Apache License

Parameter

Parameter Description
ipString a parameter

Return

ip

Declaration

public static Long getLongIp(String ipString) 

Method Source Code


//package com.java2s;
/*/*  w  ww .j ava  2s  .  c  o  m*/
 * Copyright 2016-present Open Networking Laboratory
 *
 * 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.
 */

import java.net.InetAddress;

public class Main {
    private static final int NUMBER_4 = 4;
    private static final int NUMBER_8 = 8;
    private static final Long NUMBER_0XFF = (long) 0xff;

    /**
     * Convert Ip from String to Long.
     *
     * @param ipString
     * @return ip
     */
    public static Long getLongIp(String ipString) {
        if (ipString == null) {
            throw new IllegalArgumentException("null input");
        }

        InetAddress ip;
        try {
            ip = InetAddress.getByName(ipString);
        } catch (Exception e) {
            throw new IllegalArgumentException("Ip is not valid" + ipString);
        }

        byte[] ipBytes = ip.getAddress();
        if (ipBytes.length != NUMBER_4) {
            throw new IllegalArgumentException("only IPv4 is supported" + ipString);
        }

        long ipLong = 0;
        int j = 0;
        for (int i = ipBytes.length - 1; i >= 0; i--) {
            ipLong = ipLong | ((ipBytes[j] & NUMBER_0XFF) << (i * NUMBER_8));
            j++;
        }
        return ipLong;
    }
}

Related

  1. getLocalIPv6Address()
  2. getLocalNetWorkIp()
  3. getLocalV4Ip()
  4. getLocalV4IpList()
  5. getLongIp(byte[] buff)
  6. getPublicIP()
  7. getPublicIP()
  8. getPublicIP()
  9. getPublicIP()