java網(wǎng)絡(luò)編程之識別示例 獲取主機網(wǎng)絡(luò)接口列表
獲取主機地址信息
在Java中我們使用InetAddress類來代表目標(biāo)網(wǎng)絡(luò)地址,包括主機名和數(shù)字類型的地址信息,并且InetAddress的實例是不可變的,每個實例始終指向一個地址。InetAddress類包含兩個子類,分別對應(yīng)兩個IP地址的版本:
Inet4Address
Inet6Address
我們通過前面的筆記可以知道:IP地址實際上是分配給主機與網(wǎng)絡(luò)之間的連接,而不是主機本身,NetworkInterface類提供了訪問主機所有接口的信息的功能。下面我們通過一個簡單的示例程序來學(xué)習(xí)如何獲取網(wǎng)絡(luò)主機的地址信息:
importjava.net.*;
importjava.util.Enumeration;
publicclassInetAddressExample{
publicstaticvoidmain(String[]args){
//TODOAuto-generatedmethodstub
try{
//獲取主機網(wǎng)絡(luò)接口列表
Enumeration<NetworkInterface>interfaceList=NetworkInterface
.getNetworkInterfaces();
//檢測接口列表是否為空,即使主機沒有任何其他網(wǎng)絡(luò)連接,回環(huán)接口(loopback)也應(yīng)該是存在的
if(interfaceList==null){
System.out.println("--沒有發(fā)現(xiàn)接口--");
}else{
while(interfaceList.hasMoreElements()){
//獲取并打印每個接口的地址
NetworkInterfaceiface=interfaceList.nextElement();
//打印接口名稱
System.out.println("Interface"+iface.getName()+";");
//獲取與接口相關(guān)聯(lián)的地址
Enumeration<InetAddress>addressList=iface
.getInetAddresses();
//是否為空
if(!addressList.hasMoreElements()){
System.out.println("\t(沒有這個接口相關(guān)的地址)");
}
//列表的迭代,打印出每個地址
while(addressList.hasMoreElements()){
InetAddressaddress=addressList.nextElement();
System.out
.print("\tAddress"
+((addressinstanceofInet4Address?"(v4)"
:addressinstanceofInet6Address?"v6"
:"(?)")));
System.out.println(":"+address.getHostAddress());
}
}
}
}catch(SocketExceptionse){
System.out.println("獲取網(wǎng)絡(luò)接口錯誤:"+se.getMessage());
}
//獲取從命令行輸入的每個參數(shù)所對應(yīng)的主機名和地址,迭代列表并打印
for(Stringhost:args){
try{
System.out.println(host+":");
InetAddress[]addressList=InetAddress.getAllByName(host);
for(InetAddressaddress:addressList){
System.out.println("\t"+address.getHostName()+"/"
+address.getHostAddress());
}
}catch(UnknownHostExceptione){
System.out.println("\t無法找到地址:"+host);
}
}
}
}
相關(guān)文章
SpringBoot中Elasticsearch的連接配置原理與使用詳解
Elasticsearch是一種開源的分布式搜索和數(shù)據(jù)分析引擎,它可用于全文搜索、結(jié)構(gòu)化搜索、分析等應(yīng)用場景,本文主要介紹了SpringBoot中Elasticsearch的連接配置原理與使用詳解,感興趣的可以了解一下2023-09-09
Spring集成MyBatis和PageHelper分頁插件整合過程詳解
Spring?整合?MyBatis?是將?MyBatis?數(shù)據(jù)訪問框架與?Spring?框架進行集成,以實現(xiàn)更便捷的開發(fā)和管理,在集成過程中,Spring?提供了許多特性和功能,如依賴注入、聲明式事務(wù)管理、AOP?等,這篇文章主要介紹了Spring集成MyBatis和PageHelper分頁插件整合,需要的朋友可以參考下2023-08-08
導(dǎo)致MyEclipse內(nèi)存不足的原因分析及解決辦法
這篇文章主要介紹了導(dǎo)致MyEclipse內(nèi)存不足的原因分析及解決辦法的相關(guān)資料,需要的朋友可以參考下2016-01-01
詳解Spring cloud使用Ribbon進行Restful請求
這篇文章主要介紹了詳解Spring cloud使用Ribbon進行Restful請求,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-04-04

