c4 Internet Address - The NetworkInterface class

本文介绍了Java中NetworkInterface类的使用方法,包括通过名称获取网络接口、通过IP地址获取网络接口以及获取所有网络接口等操作。同时展示了如何列举特定接口的所有IP地址。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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());
		}












评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值