Java IP Address to Byte Array ipv4ToBytes(String ipv4)

Here you can find the source of ipv4ToBytes(String ipv4)

Description

IPv4 String to bytes.

License

Apache License

Parameter

Parameter Description
ipv4 a parameter

Return

null if invalid

Declaration

public static byte[] ipv4ToBytes(String ipv4) 

Method Source Code

//package com.java2s;
/**// w  w w .j a va  2  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 String to bytes.
     *
     * @param ipv4
     * @return null if invalid
     */
    public static byte[] ipv4ToBytes(String ipv4) {
        if (ipv4 == null || ipv4.isEmpty()) {
            return null;
        }
        final String[] segments = ipv4.split("\\.", -1);
        if (segments.length != 4) {
            return null;
        }
        final byte[] ret = new byte[4];
        int val;
        for (int i = 0; i < 4; i++) {
            try {
                val = Integer.parseInt(segments[i]);
            } catch (NumberFormatException e) {
                return null;
            }
            if (val < 0 || val > 0xff) {
                return null;
            }
            ret[i] = (byte) (val & 0xff);
        }
        return ret;
    }

    public static int parseInt(final String ipv4) {

        final int position1 = ipv4.indexOf('.');
        final int position2 = ipv4.indexOf('.', position1 + 1);
        final int position3 = ipv4.indexOf('.', position2 + 1);

        return ((Integer.parseInt(ipv4.substring(0, position1)) & 0xFF) << 24)
                | ((Integer.parseInt(ipv4.substring(position1 + 1, position2)) & 0xFF) << 16)
                | ((Integer.parseInt(ipv4.substring(position2 + 1, position3)) & 0xFF) << 8)
                | ((Integer.parseInt(ipv4.substring(position3 + 1)) & 0xFF));
    }
}

Related

  1. IpToBytes(String ip)
  2. ipToBytesByReg(String ipAddr)
  3. ipv4StringToByteArrayUnchecked(String str)
  4. ipv4ToBinary(String ip)
  5. ipv4ToBytes(String ipv4)