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

2019-10-16 22:28:07

在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.tw511.com");
      System.out.println("Host name is: "+addr.getHostName());
      System.out.println("Ip address is: "+ addr.getHostAddress());
   }
}

上述程式碼範例將產生以下結果 -

Host name is: www.tw511.com
Ip address is: 112.124.103.85

範例-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();
        }
    }
}

上述程式碼範例將產生以下結果(輸出頁面原始碼) -

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