來源自 這裡Preface:The
InetAddress class can be used to perform
Domain Name Server (
DNS) lookups. For example, you can call the static
InetAddress.getByName("www.teamcakes.com")to retrieve an
InetAddress object for 'www.teamcakes.com'. This object would contain the canonical name, host name, and ip address of 'www.teamcakes.com'.
The
DnsTest class below demonstrates
InetAddress.getLocalHost(), which obtains an Internet Address for your local host. It also demonstrates
InetAddress.getByName("www.google.com"), which gives an Internet Address object for 'www.google.com'. However, it should be noted that a DNS name can map to multiple servers, and the
InetAddress.getAllByName("www.google.com") call retrieves an array of
InetAddress objects that represent all of the 'www.google.com' servers retrieved from DNS.
DnsTest 範例代碼:
- package test;
-
- import java.net.InetAddress;
- import java.net.UnknownHostException;
-
- public class DnsTest {
- public static void main(String[] args) {
- try {
- InetAddress inetAddress = InetAddress.getLocalHost();
- displayStuff("local host", inetAddress);
- System.out.print("--------------------------");
- inetAddress = InetAddress.getByName("www.google.com");
- displayStuff("www.google.com", inetAddress);
- System.out.print("--------------------------");
- InetAddress[] inetAddressArray = InetAddress.getAllByName("www.google.com");
- for (int i = 0; i < inetAddressArray.length; i++) {
- displayStuff("www.google.com #" + (i + 1), inetAddressArray[i]);
- }
- } catch (UnknownHostException e) {
- e.printStackTrace();
- }
- }
-
- public static void displayStuff(String whichHost, InetAddress inetAddress) {
- System.out.println("--------------------------");
- System.out.println("Which Host:" + whichHost);
- System.out.println("Canonical Host Name:" + inetAddress.getCanonicalHostName());
- System.out.println("Host Name:" + inetAddress.getHostName());
- System.out.println("Host Address:" + inetAddress.getHostAddress());
- }
- }
輸出結果:
--------------------------
Which Host:local host
Canonical Host Name:John-Lee
Host Name:John-Lee
Host Address:192.168.6.1
----------------------------------------------------
Which Host:www.google.com
Canonical Host Name:tf-in-f99.1e100.net
Host Name:www.google.com
Host Address:173.194.72.99
----------------------------------------------------
Which Host:www.google.com #1
Canonical Host Name:tf-in-f99.1e100.net
Host Name:www.google.com
Host Address:173.194.72.99
--------------------------
...
--------------------------
Which Host:www.google.com #6
Canonical Host Name:tf-in-f105.1e100.net
Host Name:www.google.com
Host Address:173.194.72.105
--------------------------
Which Host:www.google.com #7
Canonical Host Name:2404:6800:4008:c01:0:0:0:6a
Host Name:www.google.com
Host Address:2404:6800:4008:c01:0:0:0:6a
This message was edited 2 times. Last update was at 15/07/2013 10:24:50