A convenient method that accepts an IP address represented as a long and returns an byte array of size 4 representing the same IP address. - Java Network

Java examples for Network:IP Address

Description

A convenient method that accepts an IP address represented as a long and returns an byte array of size 4 representing the same IP address.

Demo Code

/*/* ww  w  .j  a  v  a 2 s . c om*/
 * This file is part of VIUtils.
 *
 * Copyright ? 2012-2015 Visual Illusions Entertainment
 *
 * VIUtils is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with this library.
 * If not, see http://www.gnu.org/licenses/lgpl.html.
 */
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static net.visualillusionsent.utils.Verify.notNull;

public class Main{
    public static void main(String[] argv) throws Exception{
        long address = 2;
        System.out.println(java.util.Arrays.toString(longToIPv4(address)));
    }
    /**
     * A convenient method that accepts an IP address represented as a long and
     * returns an byte array of size 4 representing the same IP address.
     *
     * @param address
     *         the long value representing the IP address.
     *
     * @return An {@code byte[]} of size 4.
     */
    public static byte[] longToIPv4(long address) {
        byte[] ip = new byte[4];
        for (int index = 0; index < 4; index++) {
            ip[index] = (byte) (address % 256);
            address = address / 256;
        }
        return ip;
    }
}

Related Tutorials