Java Socket編程:如何識別網絡主機
通過前面的筆記我們可以知道:一個客戶端想要發(fā)起一次通信,先決條件就是需要知道運行著服務器端程序的主機的IP地址是多少。然后我們才能夠通過這個地址向服務器發(fā)送信息。
獲取主機地址信息
在Java中我們使用InetAddress類來代表目標網絡地址,包括主機名和數(shù)字類型的地址信息,并且InetAddress的實例是不可變的,每個實例始終指向一個地址。InetAddress類包含兩個子類,分別對應兩個IP地址的版本:
- Inet4Address
- Inet6Address
我們通過前面的筆記可以知道:IP地址實際上是分配給主機與網絡之間的連接,而不是主機本身,NetworkInterface類提供了訪問主機所有接口的信息的功能。下面我們通過一個簡單的示例程序來學習如何獲取網絡主機的地址信息:
- import java.net.*;
- import java.util.Enumeration;
- public class InetAddressExample {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- try {
- // 獲取主機網絡接口列表
- Enumeration<NetworkInterface> interfaceList = NetworkInterface
- .getNetworkInterfaces();
- // 檢測接口列表是否為空,即使主機沒有任何其他網絡連接,回環(huán)接口(loopback)也應該是存在的
- if (interfaceList == null) {
- System.out.println("--沒有發(fā)現(xiàn)接口--");
- } else {
- while (interfaceList.hasMoreElements()) {
- // 獲取并打印每個接口的地址
- NetworkInterface iface = interfaceList.nextElement();
- // 打印接口名稱
- System.out.println("Interface" + iface.getName() + ";");
- // 獲取與接口相關聯(lián)的地址
- Enumeration<InetAddress> addressList = iface
- .getInetAddresses();
- // 是否為空
- if (!addressList.hasMoreElements()) {
- System.out.println("\t(沒有這個接口相關的地址)");
- }
- // 列表的迭代,打印出每個地址
- while (addressList.hasMoreElements()) {
- InetAddress address = addressList.nextElement();
- System.out
- .print("\tAddress"
- + ((address instanceof Inet4Address ? "(v4)"
- : address instanceof Inet6Address ? "v6"
- : "(?)")));
- System.out.println(":" + address.getHostAddress());
- }
- }
- }
- } catch (SocketException se) {
- System.out.println("獲取網絡接口錯誤:" + se.getMessage());
- }
- // 獲取從命令行輸入的每個參數(shù)所對應的主機名和地址,迭代列表并打印
- for (String host : args) {
- try {
- System.out.println(host + ":");
- InetAddress[] addressList = InetAddress.getAllByName(host);
- for (InetAddress address : addressList) {
- System.out.println("\t" + address.getHostName() + "/"
- + address.getHostAddress());
- }
- } catch (UnknownHostException e) {
- System.out.println("\t無法找到地址:" + host);
- }
- }
- }
- }
查看運行效果:
總結:
在Java Socket編程中獲取主機地址信息最關鍵的兩個類是:InetAddress和NetworkInterface,在Socket編程時必須了解這兩個類的常用API和并且熟練的使用它們。
參考資料:《TCP/IP Socket in Java》
原文鏈接:http://www.cnblogs.com/IPrograming
【編輯推薦】