Java IP Address to Int ip2int(String ipAddr)

Here you can find the source of ip2int(String ipAddr)

Description

ipint

License

Apache License

Declaration

public static int ip2int(String ipAddr) 

Method Source Code

//package com.java2s;
/*/*from   w  w  w  . java2s.  c  o  m*/
 * Copyright 2015 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.
 *
 */

public class Main {
    public static int ip2int(String ipAddr) {
        byte[] bytes = ip2bytes(ipAddr);
        int addr = bytes[3] & 0xFF;
        addr |= ((bytes[2] << 8) & 0xFF00);
        addr |= ((bytes[1] << 16) & 0xFF0000);
        addr |= ((bytes[0] << 24) & 0xFF000000);
        return addr;
    }

    public static byte[] ip2bytes(String ipAddr) {
        byte[] ret = new byte[4];
        try {
            String[] ipArr = ipAddr.split("\\.");
            ret[0] = (byte) (Integer.parseInt(ipArr[0]) & 0xFF);
            ret[1] = (byte) (Integer.parseInt(ipArr[1]) & 0xFF);
            ret[2] = (byte) (Integer.parseInt(ipArr[2]) & 0xFF);
            ret[3] = (byte) (Integer.parseInt(ipArr[3]) & 0xFF);
            return ret;
        } catch (Exception e) {
            throw new IllegalArgumentException(ipAddr + " is invalid IP");
        }

    }
}

Related

  1. ip2Int(String addr)
  2. ip2int(String ip)
  3. ip2Int(String ip)
  4. IP2Int(String ip)
  5. ipToInt(final String addr)
  6. ipToInt(String addr)
  7. ipToInt(String address)
  8. ipToInt(String ip)