获取主机网络接口与地址信息示例
获取主机地址信息
在Java中,我们利用InetAddress类来表示目标网络地址,该对象包含主机名以及数字类型的地址信息。InetAddress的实例具有不可变性,一旦创建便始终指向同一个地址。此类包含两个子类,分别对应两种版本的IP地址: 复制代码 代码如下: Inet4Address Inet6Address
根据之前的笔记可知,IP地址实际上是分配给主机与网络之间的连接,而非主机本身。NetworkInterface类提供了访问主机所有接口信息的功能。下面通过一个简单的示例程序来学习如何获取网络主机的地址信息:
复制代码 代码如下: 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); } } } }