NetworkInterface 代表本地的网络硬件,可以是物理的(比如网卡)也可以是指定到具体硬件上的虚拟interface。NetworkInterface提供了方法遍历本地的interface,然后从NetworkInterface 对象 可以得到InetAddress。
Factory Method
public static NetworkInterface getByName(String name) throws SocketException
如果没有对应名称的interface,返回null,如果遇到问题,报SocketException。
名称格式与平台有关。在Unix上像eth0,eth1,在Windows上像CE31,EXL100。
try {
NetworkInterface ni = NetworkInterface.getByName("eth0");
if (ni == null) {
System.err.println("No such interface: eth0");
}
} catch (SocketException ex) {
System.err.println("Could not list sockets.");
}
public static NetworkInterface getByInetAddress(InetAddress address) throws SocketException
try {
InetAddress local = InetAddress.getByName("127.0.0.1");
NetworkInterface ni = NetworkInterface.getByInetAddress(local);
if (ni == null) {
System.err.println("That's weird. No local loopback address.");
}
} catch (SocketException ex) {
System.err.println("Could not list network interfaces." );
} catch (UnknownHostException ex) {
System.err.println("That's weird. Could not lookup 127.0.0.1.");
}
public static Enumeration getNetworkInterfaces() throws SocketException
获取本地host上所有network interface
Enumeration<NetworkInterface> interfaces = NetworkInterface
.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface ni = interfaces.nextElement();
System.out.println(ni);
}
Getter Method
public Enumeration getInetAddresses()
NetworkInterface eth0 = NetworkInterface.getByName("eth0");
Enumeration addresses = eth0.getInetAddresses();
while (addresses.hasMoreElements()) {
System.out.println(addresses.nextElement());
}