当前位置:主页 > 软件编程 > JAVA代码 >

java网络编程之识别示例 获取主机网络接口列表

时间:2020-10-09 13:09:13 | 栏目:JAVA代码 | 点击:


获取主机地址信息

在Java中我们使用InetAddress类来代表目标网络地址,包括主机名和数字类型的地址信息,并且InetAddress的实例是不可变的,每个实例始终指向一个地址。InetAddress类包含两个子类,分别对应两个IP地址的版本:

复制代码 代码如下:

Inet4Address
Inet6Address

我们通过前面的笔记可以知道:IP地址实际上是分配给主机与网络之间的连接,而不是主机本身,NetworkInterface类提供了访问主机所有接口的信息的功能。下面我们通过一个简单的示例程序来学习如何获取网络主机的地址信息:

复制代码 代码如下:

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

publicclassInetAddressExample{

publicstaticvoidmain(String[]args){
//TODOAuto-generatedmethodstub
try{
//获取主机网络接口列表
Enumeration<NetworkInterface>interfaceList=NetworkInterface
.getNetworkInterfaces();
//检测接口列表是否为空,即使主机没有任何其他网络连接,回环接口(loopback)也应该是存在的
if(interfaceList==null){
System.out.println("--没有发现接口--");
}else{
while(interfaceList.hasMoreElements()){
//获取并打印每个接口的地址
NetworkInterfaceiface=interfaceList.nextElement();
//打印接口名称
System.out.println("Interface"+iface.getName()+";");
//获取与接口相关联的地址
Enumeration<InetAddress>addressList=iface
.getInetAddresses();
//是否为空
if(!addressList.hasMoreElements()){
System.out.println("\t(没有这个接口相关的地址)");
}
//列表的迭代,打印出每个地址
while(addressList.hasMoreElements()){
InetAddressaddress=addressList.nextElement();
System.out
.print("\tAddress"
+((addressinstanceofInet4Address?"(v4)"
:addressinstanceofInet6Address?"v6"
:"(?)")));
System.out.println(":"+address.getHostAddress());
}
}
}
}catch(SocketExceptionse){
System.out.println("获取网络接口错误:"+se.getMessage());
}
//获取从命令行输入的每个参数所对应的主机名和地址,迭代列表并打印
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);
}
}
}
}

您可能感兴趣的文章:

相关文章