不论是PC还是移动设备,都有可能同时存在几个IP地址(如具有多块网卡),本文介绍怎样获得PC或移动设备的所有IP地址。
class="brush:java;gutter:true;"> // 获得所有IP地址 public static void get_ip(){ String address; Enumeration netInterfaces; NetworkInterface ni; Enumeration cardipaddress; InetAddress ip; try { netInterfaces = NetworkInterface.getNetworkInterfaces(); while (netInterfaces.hasMoreElements()) { ni = (NetworkInterface) netInterfaces.nextElement(); cardipaddress = ni.getInetAddresses(); while (cardipaddress.hasMoreElements()) { ip = (InetAddress) cardipaddress.nextElement(); if(!ip.getHostAddress().equalsIgnoreCase("127.0.0.1") ) { address = ip.getHostAddress(); c_lip.addItem(address); } } } } catch (Exception e) { } }
首先,用NetworkInterface的getNetworkInterfaces()获得所有的NetworkInterfaces,对每一个NetworkInterface,再用getInetAddresses()获得它的IP地址,对于非127.0.0.1的地址,将其加入列表框中。
PC的运行结果如下: