importjava.net.*;
importjava.util.Enumeration;
publicclassInetAddressExample{
publicstaticvoidmain(String[]args){
//TODOAuto-generatedmethodstub
try{
//获取主机网络接口列表
EnumerationinterfaceList=NetworkInterface
.getNetworkInterfaces();
//检测接口列表是否为空,即使主机没有任何其他网络连接,回环接口(loopback)也应该是存在的
if(interfaceList==null){
System.out.println("--没有发现接口--");
}else{
while(interfaceList.hasMoreElements()){
//获取并打印每个接口的地址
NetworkInterfaceiface=interfaceList.nextElement();
//打印接口名称
System.out.println("Interface"+iface.getName()+";");
//获取与接口相关联的地址
EnumerationaddressList=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);
}
}
}
}