1. 程式人生 > >Java如何從IP地址查找主機名?

Java如何從IP地址查找主機名?

str 地址 too stat class ati specific ace 查詢

在Java編程中,如何從IP地址查詢出主機名?

以下示例顯示了如何通過net.InetAddress類的InetAddress.getByName()方法將指定的IP地址查到主機名稱。

package com.yiibai;


import java.net.InetAddress;

public class HostSpecificByIP {
   public static void main(String[] argv) throws Exception {
      InetAddress addr = InetAddress.getByName("www.yiibai.com");
      System.out.println("Host name is: "+addr.getHostName());
      System.out.println("Ip address is: "+ addr.getHostAddress());
   }
}
Java

上述代碼示例將產生以下結果 -

Host name is: www.yiibai.com
Ip address is: 112.124.103.85
Shell

示例-2

從IP地址查找主機名的另一個示例:

package com.yiibai;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class HostSpecificByIP2 {
    public static void main(String[] args) {
        InetAddress ip;
        String hostname;
        try {
            ip = InetAddress.getLocalHost();
            hostname = ip.getHostName();
            System.out.println("Your current IP address : " + ip);
            System.out.println("Your current Hostname : " + hostname);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}
Java

上述代碼示例將產生以下結果(輸出頁面源代碼) -

Your current IP address : YB-PC/192.168.1.50
Your current Hostname : YB-PC

Java如何從IP地址查找主機名?