集册 Java实例教程 给定一个数字字符串格式的ip,返回InetAddress。

给定一个数字字符串格式的ip,返回InetAddress。

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

631
给定一个数字字符串格式的ip,返回InetAddress。


//package com.nowjava;/**来 自 时   代    Java - nowjava.com**/

import java.net.InetAddress;

import java.net.UnknownHostException;


public class Main {

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

        String ip = "nowjava.com";

        System.out.println(parseNumericIp(ip));

    }


    /**

     * Given an ip in a numeric, string format, return the InetAddress.

     * @param ip the ip address in string format (such as 3232235780)

     * @return the InetAddress object (such as the object representing 192.168.1.4)

     */

    public static InetAddress parseNumericIp(String ip) {

        return parseNumericIp(Long.parseLong(ip));

    }


    /**

     * Given an ip in numeric format, return the InetAddress.

     * @param ip the ip address in long (such as 3232235780)

     * @return the InetAddress object (such as the object representing 192.168.1.4)

     */

    public static InetAddress parseNumericIp(long ip) {

        try {

            return InetAddress.getByAddress(numericIpToByteArray(ip));

        } catch (UnknownHostException e) {//n o w  j a v a  . c o m

            return null;

        }

    }


    /**

     * Given an ip in numeric format, return a byte array that can be fed to

     * InetAddress.

     * @param ip the ip address in long (such as 3232235780)

     * @return the byte array.

     */

    public static byte[] numericIpToByteArray(long ip) {

        byte[] ipArray = new 
展开阅读全文