Java如何根據主機名(域名)獲取IP地址?

2019-10-16 22:27:54

在Java程式設計中,如何根據主機名(域名)獲取IP地址?

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

package com.yiibai;

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

public class HostSpecificIPAddress {
   public static void main(String[] args) {
      InetAddress address = null;
      try {
         address = InetAddress.getByName("www.tw511.com");
      } catch (UnknownHostException e) {
         System.exit(2);
      }
      System.out.println(address.getHostName() + " IP is = " + address.getHostAddress());
      System.exit(0);
   }
}

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

www.tw511.com IP is = 112.124.103.85

範例-2

以下是Java中使用getHostAddress()getHostName()獲取本機的另一個範例 -

package com.yiibai;

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

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

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

Your IP address : Yiibai-PC/192.168.1.50
Your Hostname : Yiibai-PC