Convert an integer into an IPv4 INET address. - Java Network

Java examples for Network:IP Address

Description

Convert an integer into an IPv4 INET address.

Demo Code

/*//from  w w w  .j ava  2  s.  co  m
 * Copyright (c) 2004 by Cosylab
 *
 * The full license specifying the redistribution, modification, usage and other
 * rights and obligations is included with the distribution of this project in
 * the file "LICENSE-CAJ". If the license is not included visit Cosylab web site,
 * <http://www.cosylab.com>.
 *
 * THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY OF ANY KIND, NOT EVEN THE
 * IMPLIED WARRANTY OF MERCHANTABILITY. THE AUTHOR OF THIS SOFTWARE, ASSUMES
 * _NO_ RESPONSIBILITY FOR ANY CONSEQUENCE RESULTING FROM THE USE, MODIFICATION,
 * OR REDISTRIBUTION OF THIS SOFTWARE.
 */
//package com.java2s;

import java.net.InetAddress;

import java.net.UnknownHostException;

public class Main {
    public static void main(String[] argv) throws Exception {
        int addr = 2;
        System.out.println(intToIPv4Address(addr));
    }

    /**
     * Convert an integer into an IPv4 INET address.
     * @param addr integer representation of a given address.
     * @return IPv4 INET address.
     */
    public static InetAddress intToIPv4Address(int addr) {
        byte[] a = new byte[4];

        a[0] = (byte) ((addr >> 24) & 0xFF);
        a[1] = (byte) ((addr >> 16) & 0xFF);
        a[2] = (byte) ((addr >> 8) & 0xFF);
        a[3] = (byte) ((addr & 0xFF));

        InetAddress res = null;
        try {
            res = InetAddress.getByAddress(a);
        } catch (UnknownHostException e) { /* noop */
        }

        return res;
    }
}

Related Tutorials