Java IP Address Convert To convertIpv4Address(String ip)

Here you can find the source of convertIpv4Address(String ip)

Description

Convert an IPv4 address string representation into a sequence of 4 bytes.

License

Open Source License

Parameter

Parameter Description
ip The IP address string to be converted

Return

The array of 4 bytes corresponding to each encoded value, or a null array if the address is invalid in any way.

Declaration

public static byte[] convertIpv4Address(String ip) 

Method Source Code

//package com.java2s;

public class Main {
    /**//from  w  w w  . ja  v  a2 s . c om
     * The maximum decimal value that can be assigned a single byte of an IPv4 dotted notation address.
     */
    private static final int IPV4_MAX_SEGMENT_VALUE = 255;
    /**
     * The number of bytes that comprise an IPv4 address
     */
    private static final int IPV4_BYTE_COUNT = 4;

    /**
     * Convert an IPv4 address string representation into a sequence of 4 bytes.
     * 
     * @param ip
     *            The IP address string to be converted
     * @return The array of 4 bytes corresponding to each encoded value, or a null array if the address is invalid in
     *         any way.
     */
    public static byte[] convertIpv4Address(String ip) {

        String[] tokens = ip.split("\\.");
        if (tokens.length != IPV4_BYTE_COUNT) {
            return null;
        }
        byte[] bytes = new byte[IPV4_BYTE_COUNT];
        for (int index = 0; index < IPV4_BYTE_COUNT; index++) {
            try {
                int value = Integer.parseInt(tokens[index]);
                if (value < 0 || value > IPV4_MAX_SEGMENT_VALUE) {
                    return null;
                }
                bytes[index] = (byte) value;
            } catch (NumberFormatException e) {
                return null;
            }
        }

        return bytes;
    }
}

Related

  1. convertIp(String ip)
  2. convertIP6Address(byte[] bytes)
  3. convertIPAdressToBytes(String ip)
  4. convertIpPortToUniqueId(byte[] quad, int port)
  5. convertIpv4AddressToString(byte[] ipv4Address)
  6. convertIPv4NetworkPrefixLength(short length)
  7. convertIpv4ToIpv6(String ip)
  8. convertIpv6Address(String ip)