From Gossip@Openhome

Java Gossip: InetAddress 類別

網路程式的第一步通常是從網址資訊的處理開始,這很容易理解,如果連網址都無法取得,更別談網路連線了。

java.net.InetAddress類別可用來包裝與進行網址處理的相關操作,它要有幾個靜態方法傳回InetAddress物件:
public static InetAddress InetAddress.getLocalHost()
public static InetAddress InetAddress.getByName(String hostname)
public static InetAddress[] InetAddress.getAllByName(String hostname)

InetAddress主要包括兩個欄位(field),即名稱與位址,名稱即像是openhome.cc這樣的名稱, 而位址則是IP位址,我們可以使用getHostName()與getHostAddress()方法分別取得這兩個資訊。

getLocalhost()可以取得本機網址資訊,下面這個簡單的程式即可顯示本機名稱與位址:
  • Host.java
package onlyfun.caterpillar;

import java.net.*;

public class Host {
public static void main(String[] args) {
try {
InetAddress address = InetAddress.getLocalHost();
System.out.println(address);
System.out.printf("HostName: %s%n", address.getHostName());
System.out.printf("HostAddress: %s%n", address.getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}

執行結果:
caterpillar-PC/192.168.1.23
HostName: caterpillar-PC
HostAddress: 192.168.1.23


下面的程式也很簡單,可以指定查詢遠端主機的名稱與IP位址:
  • Host.java
package onlyfun.caterpillar;

import java.net.*;

public class Host {
public static void main(String[] args) {
try {
InetAddress address = InetAddress.getByName(args[0]);
System.out.println(address);
System.out.printf("HostName: %s%n", address.getHostName());
System.out.printf("HostAddress: %s%n", address.getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}

執行結果:
java onlyfun.caterpillar.Host openhome.cc
openhome.cc/64.22.69.61
HostName: openhome.cc
HostAddress: 64.22.69.61


有的網站上可能擁有不止一個的IP位址,可以使用getAllByName()方法取回所有的網址資訊,這會傳回InetAddress物件陣列,可以使用迴圈將這些物件一一取出,下面的程式是一個簡單的示範:
  • Host.java
package onlyfun.caterpillar;

import java.net.*;

public class Host {
public static void main(String[] args) {
try {
InetAddress[] addresses = InetAddress.getAllByName(args[0]);
for(int i = 0; i < addresses.length; i++)
System.out.println(addresses[i]);
}
catch(UnknownHostException e) {
e.printStackTrace();
}
}
}

執行結果:
java onlyfun.caterpillar.Host cnn.com
cnn.com/64.236.16.20
cnn.com/64.236.16.52
cnn.com/64.236.24.12
cnn.com/64.236.29.120