集册 Java实例教程 将整数转换为IPv4 INET地址。

将整数转换为IPv4 INET地址。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

403
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
将整数转换为IPv4 INET地址。

/*

 * 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.nowjava;


import java.net.InetAddress;/*来 自 N  o w  J a v a . c o m*/


import java.net.UnknownHostException;


public class Main {

    public static void main(String[] argv) throws Exception {

        int addr = 2;

        System.out.println(intToIPv4Address(addr));

    }
/**来自 时 代 J a v a 公 众 号 - N o w J a v  a . c o m**/

    /**

     * 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] = (
展开阅读全文