亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

java網(wǎng)絡(luò)編程之識(shí)別示例 獲取主機(jī)網(wǎng)絡(luò)接口列表

 更新時(shí)間:2014年01月22日 16:22:33   作者:  
一個(gè)客戶端想要發(fā)起一次通信,先決條件就是需要知道運(yùn)行著服務(wù)器端程序的主機(jī)的IP地址是多少。然后我們才能夠通過(guò)這個(gè)地址向服務(wù)器發(fā)送信息。


獲取主機(jī)地址信息

在Java中我們使用InetAddress類來(lái)代表目標(biāo)網(wǎng)絡(luò)地址,包括主機(jī)名和數(shù)字類型的地址信息,并且InetAddress的實(shí)例是不可變的,每個(gè)實(shí)例始終指向一個(gè)地址。InetAddress類包含兩個(gè)子類,分別對(duì)應(yīng)兩個(gè)IP地址的版本:

復(fù)制代碼 代碼如下:

Inet4Address
Inet6Address

我們通過(guò)前面的筆記可以知道:IP地址實(shí)際上是分配給主機(jī)與網(wǎng)絡(luò)之間的連接,而不是主機(jī)本身,NetworkInterface類提供了訪問(wèn)主機(jī)所有接口的信息的功能。下面我們通過(guò)一個(gè)簡(jiǎn)單的示例程序來(lái)學(xué)習(xí)如何獲取網(wǎng)絡(luò)主機(jī)的地址信息:

復(fù)制代碼 代碼如下:

importjava.net.*;
importjava.util.Enumeration;

publicclassInetAddressExample{

publicstaticvoidmain(String[]args){
//TODOAuto-generatedmethodstub
try{
//獲取主機(jī)網(wǎng)絡(luò)接口列表
Enumeration<NetworkInterface>interfaceList=NetworkInterface
.getNetworkInterfaces();
//檢測(cè)接口列表是否為空,即使主機(jī)沒(méi)有任何其他網(wǎng)絡(luò)連接,回環(huán)接口(loopback)也應(yīng)該是存在的
if(interfaceList==null){
System.out.println("--沒(méi)有發(fā)現(xiàn)接口--");
}else{
while(interfaceList.hasMoreElements()){
//獲取并打印每個(gè)接口的地址
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(沒(méi)有這個(gè)接口相關(guān)的地址)");
}
//列表的迭代,打印出每個(gè)地址
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ò)接口錯(cuò)誤:"+se.getMessage());
}
//獲取從命令行輸入的每個(gè)參數(shù)所對(duì)應(yīng)的主機(jī)名和地址,迭代列表并打印
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無(wú)法找到地址:"+host);
}
}
}
}

相關(guān)文章

最新評(píng)論