Java IP Address to Byte Array ip2bytes(String ipAddr)

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

Description

ipbytes

License

Apache License

Declaration

public static byte[] ip2bytes(String ipAddr) 

Method Source Code

//package com.java2s;
/*//from w  w w . j a  va  2s .c om
 * 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 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. ip2bytes(String ip)
  2. ipToByte(String ip)
  3. ipToByte(String ip)
  4. IpToBytes(String ip)
  5. ipToBytesByReg(String ipAddr)